How to replace vector values without loop for?
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (1)
per isakson
il 8 Set 2014
Modificato: per isakson
il 8 Set 2014
Hint:
x( y(:,1)>=z(:,1), 1 ) = 1;
However, I didn't say that this is faster than the loop
1 Commento
Joseph Cheng
il 8 Set 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.
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!