How to make a series of consecutive numbers using a nested for loop?
2 views (last 30 days)
Show older comments
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 Comments
Guillaume
on 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
Accepted Answer
Jan
on 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 Comments
More Answers (2)
Jan
on 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
on 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 Comments
See Also
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!