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!