How to make a series of consecutive numbers using a nested for loop?
3 visualizzazioni (ultimi 30 giorni)
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
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
Risposta accettata
Jan
il 14 Feb 2016
It's not clear to me, what you want to achieve. So let me guess a little bit:
1. The direct approach:
L1 = 3;
L2 = 5;
a = (1:(L1*L2)).'
2. With the loops:
a = [];
c = 0;
for i = 1:3
for j = 1:5
c = c + 1;
a = [a; c]; % Prefer a pre-allocation
disp(a)
end
end
3. Using the paramters mentioned in my first answer:
a = [];
for i = 1:3
for j = 1:5
a = [a; (i - 1) * 5 + j];
disp(a)
end
end
But nothing will beat the approach 1. in speed and clarity.
0 Commenti
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
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
0 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!