For each loop upon fixed size array

34 次查看(过去 30 天)
Hi guys,
I have three variable x y z that are integer values and for instance its values are :
x=5 , y=2 , z=3;
and I have an array called A equal to A=[x y z]
I want to do for each loop upon the array A and adding +1 for every iteration of the for each loop .
I came from world of c world and rarely I use matlab (it depends on what do I want to implement ) .. how can I do that in matlab?
thanks alot for any help .

采纳的回答

David Hill
David Hill 2020-11-16
for k=1:100
A=A+1;
end
  4 个评论
Jimmy cho
Jimmy cho 2020-11-16
Can't I do that in matlab? for instance in python ..and the reason is that foreach it's more elegant that using idexes.
another question in the context, lets assume I have array A=[x y z ] and x , y , z as I said in my thread above is integer values, how I pass/run over A array by foreach in matlab code?
just like this:
for m:A
%do something with m / do arithmatic with m , m is the value of array A and next value of array A updated to m at each iteration
end
Image Analyst
Image Analyst 2020-11-16
Well most MATLABers would think
result = diff(A) > 0;
is more elegant than using for or foreach. The diff() function subtracts the kth element from the (k+1)st element.
result is a logical matrix giving essentially a "map" of what elements are greater than the prior element.

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2020-11-16
Another option
Acopy = A; % Make copy of original
for k = 1 : 100
Acopy = A + k;
end
The original A does not get changed, however Acopy still gets overwritten at each iteration.
  2 个评论
Jimmy cho
Jimmy cho 2020-11-16
" Acopy = A + k " in this statement the A is changed at every iteration to the next value organizedly ? I mean first value at 1, then next iteration value at 2 , then next iteration value at 3 ?
Jimmy cho
Jimmy cho 2020-11-16
If I understand you well, if I do this:
for k = 1 : 100
m = A ;
end
so every value of A will be copied / stored to m correspondingly , yes?
Implicitly A is going to the next value at every iteration

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by