How to replace vector values without loop for?
10 次查看(过去 30 天)
显示 更早的评论
Hi everyone, I have a vector x(1:10000,1) which elements are all 0. I want to replace 0 with 1 in the case a statement is satified. I used the following loop for to do that:
for i = 1:10000
if y(i,:) >= z(i,:)
x(i,:) = 1;
end
end
The code works properly but I would like to optimize the script process. Is there some way to do the same thing without using a loop for? Thanks for help.
0 个评论
回答(1 个)
per isakson
2014-9-8
编辑:per isakson
2014-9-8
Hint:
x( y(:,1)>=z(:,1), 1 ) = 1;
However, I didn't say that this is faster than the loop
1 个评论
Joseph Cheng
2014-9-8
well to test our your piece here is a quick test
clc
x = zeros(10000,1);
y = rand(size(x));
z = rand(size(x));
tic,
for i = 1:10000
if y(i,:) >= z(i,:)
x(i,:) = 1;
end
end
disp(['loop version time: ' num2str(toc)])
x1 = zeros(10000,1);
tic,
x1 = y>=z;
disp(['compare replace all version time: ' num2str(toc)])
x2 = zeros(10000,1);
tic
x2( y(:,1)>=z(:,1), 1 ) = 1;
disp(['replace only true version time: ' num2str(toc)])
which on my machine gets me
loop version time: 0.0088747
compare replace all version time: 0.00061254
replace only true version time: 0.00018797
Which does seem intuitive as replacing only the ones that need to be replaced is faster than replacing everything.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Problem-Based Optimization Setup 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!