l******d 发帖数: 12 | 1 Thanks for your help in advance ...
Is there a function in matlab that can accomplish what the fortran 90
intrinsic function 'where' does:
WHERE ( x >= 0.0 )
z = 4.0*sqrt(x)
ELSEWHERE
z = 0.0
END WHERE
Here x, z are both vectors.
I assume matlab must have something similar, otherwise, looping over every
element of x would be too expensive. Thank you very much~~~ |
l*****i 发帖数: 3929 | 2 z = zeros(size(x));
ind = find(x>=0);
z(ind) = 4*sqrt(x(ind));
【在 l******d 的大作中提到】 : Thanks for your help in advance ... : Is there a function in matlab that can accomplish what the fortran 90 : intrinsic function 'where' does: : WHERE ( x >= 0.0 ) : z = 4.0*sqrt(x) : ELSEWHERE : z = 0.0 : END WHERE : Here x, z are both vectors. : I assume matlab must have something similar, otherwise, looping over every
|
l******d 发帖数: 12 | 3 Answer myself:
ind=find(x>=0.);
z=zeros(1,length(x));
z(ind)=4.0*sqrt(x(ind);
【在 l******d 的大作中提到】 : Thanks for your help in advance ... : Is there a function in matlab that can accomplish what the fortran 90 : intrinsic function 'where' does: : WHERE ( x >= 0.0 ) : z = 4.0*sqrt(x) : ELSEWHERE : z = 0.0 : END WHERE : Here x, z are both vectors. : I assume matlab must have something similar, otherwise, looping over every
|
l******d 发帖数: 12 | 4 Thank you very much, I guess we arrived at the same answers.
【在 l*****i 的大作中提到】 : z = zeros(size(x)); : ind = find(x>=0); : z(ind) = 4*sqrt(x(ind));
|
c****p 发帖数: 6474 | 5 其实有更简单的形式:
z=zeros(size(x));
z(x>0)=4.0*sqrt(x(x>0));
【在 l******d 的大作中提到】 : Answer myself: : ind=find(x>=0.); : z=zeros(1,length(x)); : z(ind)=4.0*sqrt(x(ind);
|
j**u 发帖数: 6059 | 6 而且速度比用find快
【在 c****p 的大作中提到】 : 其实有更简单的形式: : z=zeros(size(x)); : z(x>0)=4.0*sqrt(x(x>0));
|
t***s 发帖数: 4666 | 7 一个要做两遍,一个做一遍。
【在 j**u 的大作中提到】 : 而且速度比用find快
|
c****p 发帖数: 6474 | 8 clear
LOOP=100000;
x=-16:.1:16;
S=size(x);
tic;
for i=1:LOOP
z=zeros(S);
z(x>0)=sqrt(x(x>0))*4;
end
toc;
tic;
for i=1:LOOP
z=zeros(S);
ind=find(x>0);
z(ind)=sqrt(x(ind))*4;
end
toc;
>> timetest
Elapsed time is 4.073553 seconds.
Elapsed time is 4.463364 seconds.
【在 t***s 的大作中提到】 : 一个要做两遍,一个做一遍。
|
t***s 发帖数: 4666 | 9 how about ind=x>0;z(ind)=sqrt(x(ind));
and your matrix is too small. overhead too much.
【在 c****p 的大作中提到】 : clear : LOOP=100000; : x=-16:.1:16; : S=size(x); : tic; : for i=1:LOOP : z=zeros(S); : z(x>0)=sqrt(x(x>0))*4; : end : toc;
|
t***s 发帖数: 4666 | 10 >> x = randn(5000);
>> z = zeros(size(x));
>> tic;z(x>0)=sqrt(x(x>0))*4;toc;
Elapsed time is 3.653124 seconds.
>> tic;ind=x>0;z(ind)=sqrt(x(ind))*4;toc;
Elapsed time is 3.310924 seconds.
>>
【在 t***s 的大作中提到】 : how about ind=x>0;z(ind)=sqrt(x(ind)); : and your matrix is too small. overhead too much.
|
c****p 发帖数: 6474 | 11 嗯,这样更好。
总之用find比这么整慢。
【在 t***s 的大作中提到】 : >> x = randn(5000); : >> z = zeros(size(x)); : >> tic;z(x>0)=sqrt(x(x>0))*4;toc; : Elapsed time is 3.653124 seconds. : >> tic;ind=x>0;z(ind)=sqrt(x(ind))*4;toc; : Elapsed time is 3.310924 seconds. : >>
|