inverse loop
Show older comments
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 Comment
Amr
on 12 Oct 2016
sure ... use this command for i=180:-1:1 for j=180:-1:1
Answers (3)
Jan
on 22 Nov 2011
Edited: Walter Roberson
on 1 Sep 2024
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
on 22 Nov 2011
Try,
for i=180:-1:1
for j =180:-1:1
i
j
end
end
5 Comments
MH
on 1 Sep 2024
@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
on 1 Sep 2024
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
on 1 Sep 2024
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
on 1 Sep 2024
Thank you @Walter Roberson
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!