gpt4 book ai didi

matlab - 将函数应用于矩阵,这取决于索引?

转载 作者:太空宇宙 更新时间:2023-11-03 19:54:55 24 4
gpt4 key购买 nike

假设我有一个矩阵A,我想对它的每个元素应用一个函数f。然后我可以使用 f(A),如果 f 是矢量化的,或者 arrayfun(f,A) 如果不是。

但是如果我有一个依赖于条目及其索引的函数怎么办:f = @(i,j,x) something。如何在不使用如下所示的 for 循环的情况下将此函数应用于矩阵 A

for j=1:size(A,2)
for i=1:size(A,1)
fA(i,j) = f(i,j,A(i,j));
end
end

我想考虑将函数 f 向量化。不过,欢迎提供有关非矢量化函数的更短符号的提示。

最佳答案

我已经阅读了您的回答,并且想到了另一个使用索引的想法,这是最快的方法。这是我的测试脚本:

%// Test function
f = @(i,j,x) i.*x + j.*x.^2;

%// Initialize times
tfor = 0;
tnd = 0;
tsub = 0;
tmy = 0;

%// Do the calculation 100 times
for it = 1:100

%// Random input data
A = rand(100);

%// Clear all variables
clear fA1 fA2 fA3 fA4;

%// Use the for loop
tic;
fA1(size(A,1),size(A,2)) = 0;
for j=1:size(A,2)
for i=1:size(A,1)
fA1(i,j) = f(i,j,A(i,j));
end
end
tfor = tfor + toc;

%// Use ndgrid, like @Divakar suggested
clear I J;
tic;
[I,J] = ndgrid(1:size(A,1),1:size(A,2));
fA2 = f(I,J,A);
tnd = tnd + toc;

%// Test if the calculation is correct
if max(max(abs(fA2-fA1))) > 0
max(max(abs(fA2-fA1)))
end

%// Use ind2sub, like @DennisKlopfer suggested
clear I J;
tic;
[I,J] = ind2sub(size(A),1:numel(A));
fA3 = arrayfun(f,reshape(I,size(A)),reshape(J,size(A)),A);
tsub = tsub + toc;

%// Test if the calculation is correct
if max(max(abs(fA3-fA1))) > 0
max(max(abs(fA3-fA1)))
end

%// My suggestion using indexing
clear sA1 sA2 ssA1 ssA2;
tic;
sA1=size(A,1);
ssA1=1:sA1;
sA2=size(A,2);
ssA2=1:sA2;
fA4 = f(ssA1(ones(1,sA2),:)', ssA2(ones(1,sA1,1),:), A); %'
tmy = tmy + toc;

%// Test if the calculation is correct
if max(max(abs(fA4-fA1))) > 0
max(max(abs(fA4-fA1)))
end
end

%// Print times
tfor
tnd
tsub
tmy

我得到了结果

tfor =
0.6813

tnd =
0.0341

tsub =
10.7477

tmy =
0.0171

关于matlab - 将函数应用于矩阵,这取决于索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33474863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com