How to replace vector values without loop for?

5 views (last 30 days)
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.

Answers (1)

per isakson
per isakson on 8 Sep 2014
Edited: per isakson on 8 Sep 2014
Hint:
x( y(:,1)>=z(:,1), 1 ) = 1;
However, I didn't say that this is faster than the loop
  1 Comment
Joseph Cheng
Joseph Cheng on 8 Sep 2014
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.

Sign in to comment.

Categories

Find more on Problem-Based Optimization Setup in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!