How to make a series of consecutive numbers using a nested for loop?
Mostra commenti meno recenti
Hi, I would like a generic expression to obtain an array of consecutive numbers until reaching the value of the product between the limits of two nested loops. I hope the example below will clarify the question. If I have the nested loop:
for i = 1:3
for j = 1:5
a = ????;
disp(a)
end
end
Which is the expression for 'a' that permits me to obtain a column array from 1 to 15?
a=
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Maybe there are easier way to obtain this but I must use a nested loop and the last number must be equal to the product of the two limits of the for loop (3 and 5 => 15 in this example). Many thanks.
4 Commenti
What you're asking does not make any sense to me. You want an array that goes from 1 to limit_of_loop1 * limit_of_loop2. Therefore, none of the elements in a depend in any way on what happens in the loops. You may as well calculate a outside the loops and if the loops don't do anything get rid of them
Therefore, you could just write:
limit_loop1 = 3;
limit_loop2 = 5;
%for i = 1:limit_loop1
% for j = 1:limit_loop2
%we're just wasting time with these loops!
% end
%end
a = 1:limit_loop1*limit_loop2
Giovanni Rinaldi
il 10 Feb 2016
Guillaume
il 10 Feb 2016
I still don't understand what you want. What part of a do you want to calculate in the loop? Would the following work?
limit_loop1 = 3;
limit_loop2 = 5;
for i = 1:limit_loop1
for j = 1:limit_loop2
a = 1:limit_loop1*limit_loop2; %but what's the point?
end
end
Giovanni Rinaldi
il 10 Feb 2016
Risposta accettata
Più risposte (2)
Jan
il 10 Feb 2016
This looks like a homework question. Do you really want us to solve it, or would delivering the solution made by someone else be cheating?
What about defining a=0 at the beginning and increasing a by one inside the loops?
You can find some constants b, c and d manually, such that
b * i + c * j + d = 1 % for i=1 and b=1
b * i + c * j + d = 2 % for i=1 and b=2
etc
1 Commento
Giovanni Rinaldi
il 10 Feb 2016
Guillaume
il 10 Feb 2016
Maybe one of these is what you want. It's really not clear what you want to do within the loops:
Possible solution #1:
limit_loop1 = 3;
limit_loop2 = 5;
a = zeros(limit_loop1 * limit_loop2, 1);
for i = 1:limit_loop1
for j = 1:limit_loop2
aidx = sub2ind([limit_loop1, limit_loop2], i, j);
a(aidx) = aidx;
end
end
Possible solution #2:
limit_loop1 = 3;
limit_loop2 = 5;
a = 1;
for i = 1:limit_loop1
for j = 1:limit_loop2
if i>1 || j>1
a = [a(end); a+1];
end
end
Neither of which make much sense to me, since as pointed out:
a = 1:limit_loop1*limit_loop2
gives the same result without needing the loops
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!