inverse loop
显示 更早的评论
I want to use loop from i=180:1 and again next inserted loop j=180:1 Does matlab allow that? how I access (180,180) first rather then (0,0)...
1 个评论
Amr
2016-10-12
sure ... use this command for i=180:-1:1 for j=180:-1:1
回答(3 个)
Jan
2011-11-22
编辑:Walter Roberson
2024-9-1
Whenever you have a problem with a specific command, be sure to read the help and doc text for this command:
help for
Step S with increments of -0.1
for S = 1.0: -0.1: 0.0, do_some_task(S), end
Thomas
2011-11-22
Try,
for i=180:-1:1
for j =180:-1:1
i
j
end
end
5 个评论
MH
2024-9-1
@Thomas is there a way in matlab where you can flip the nesting of the loops based a user's preference via a dialog box selection?
meaning if I have a dialog box that pops up when the code runs and asks, 'do you want to run the code as is or inverted' with two options 'as is' or 'inverted' and based on the selection, the code would either run as
for i=180:-1:1
for j =180:-1:1
i
j
end
end
OR
for j =180:-1:1
for i=180:-1:1
i
j
end
end
Without having a "switch" case
John D'Errico
2024-9-1
Of course. You could just set the limits and the step for the loops, based on a test on the result returned from the dialog box.
for i = start:step:fin
for j = start:step:fin
i
j
end
end
Just define the values of start, step, and fin, and you are done.
Don't try to dynamically change the code. Change the data.
x = 1:5;
if rand > 0.5
fprintf("Flipping loop vector")
x = flip(x);
end
for k = x
fprintf("Processing element %d.\n", k)
end
Depending on the random value generated when you run the code, x will be either 1:5 or 5:-1:1. The for loop will iterate over the elements in that vector. [In this case the value was greater than 0.5 so the vector got flipped, as you can see from the iterative output.]
In your case, the decision to flip or not to flip could be made based on a prompt from the user or some other computations, but the input function is not supported in answers posted on MATLAB Answers.
Walter Roberson
2024-9-1
The question @MH asked is about automatically inverting the order of two loops, without having to have a switch() statement. In one case in their example the loops are nested j within i, and in the other case the loops are nested i within j.
The answer to the question is "No, there is no dialog box or editor option to automatically reverse the nesting order. You would need something like
for outer = start:step:fin
for inner = start:step:fin
if ReverseLoop
i = outer; j = inner;
else
i = inner; j = outer;
end
%code
end
end
MH
2024-9-1
Thank you @Walter Roberson
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!