필터 지우기
필터 지우기

increment two values in a single for loop

조회 수: 37 (최근 30일)
Duncan
Duncan 2014년 8월 11일
댓글: Steven Lord 2019년 6월 26일
I was just wondering if there was a way to increment two variables simultaneously in a single for loop?
for example i want to increment
i = 1:1:n-times
but at the same time
j=1:1:m-times
in a single for loop

답변 (3개)

Star Strider
Star Strider 2014년 8월 11일
This works:
times = 2;
m = 10;
n = 15;
j = 0
for i = 1:1:n-times
if j < m-times
j = j + 1;
end
% ... etc...
end
i % Display results
j
  댓글 수: 1
Image Analyst
Image Analyst 2014년 8월 11일
or, without the if:
j = min(i, m-times);
Just an alternate way - I have no idea which is faster.

댓글을 달려면 로그인하십시오.


Iain
Iain 2014년 8월 11일
There is a cheeky way:
for h = 1:110
[i, j] = ind2sub([10,11],h)
...
end

sourav  malla
sourav malla 2019년 6월 26일
You can also do like this:-
for i=1:n,j=1:m
%do something;
end
It will execute the stuff in (n*m) format.
  댓글 수: 1
Steven Lord
Steven Lord 2019년 6월 26일
At each iteration of the one for loop in that code, the variable j will be assigned the vector 1:m.
If you have two arrays of data:
variable1 = magic(5);
variable2 = gallery('moler', 5);
you could iterate over both with one loop if you assume or check that they have the same number of elements.
for whichElement = 1:numel(variable1)
V1 = variable1(whichElement);
V2 = variable2(whichElement);
% Do something with V1 and V2
fprintf('Element %2d of each matrix is %2d, %2d.\n', ...
whichElement, V1, V2);
end

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by