Filter löschen
Filter löschen

How to replace vector values without loop for?

10 Ansichten (letzte 30 Tage)
Quantopic
Quantopic am 8 Sep. 2014
Kommentiert: Joseph Cheng am 8 Sep. 2014
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.

Antworten (1)

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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Problem-Based Optimization Setup finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by