How to combine to identical 'for' loops with sequential varying variables ?

3 views (last 30 days)
I have two 'for' loops:
1st loop)
a1=[1 2 3 4 5];
b1=[6 7 8 9 10];
for i=1:5
c1(i)=a1(i)+b1(i)
end
2nd loop)
a2=[4 5 7 8 9];
b2=[3 2 4 5 7];
for i=1:5;
c2(i)=a2(i)+b2(i)
end
The problem: I have to combine above mentioned two 'for' loops in a such way that in each iteration (j) loop has to work with variables corresponding to j. For example if j=5
then,
for j=5;
for i=1:5
c5(i)=a5(i)+b5(i)
end
end
I will give another example for clarification (if j=6):
for j=6;
for i=1:5
c6(i)=a6(i)+b6(i)
end
end

Accepted Answer

Stephen23
Stephen23 on 14 Feb 2021
Edited: Stephen23 on 14 Feb 2021
Numbering variables like that is completely the wrong approach and should be avoided.
One better approach is to use a container array, e.g. a cell array:
a{1} = [1,2,3,4,5];
b{1} = [6,7,8,9,10];
a{2} = [4,5,7,8,9];
b{2} = [3,2,4,5,7];
n = numel(a);
c = cell(1,n);
for ii = 1:n
for jj = 1:5
c{ii}(jj)=a{ii}(jj)+b{ii}(jj);
end
end
c{:}
ans = 1×5
7 9 11 13 15
ans = 1×5
7 7 11 13 16
Of course for this example the best approach would be to use numeric arrays and vectorized operations (for the given example using loops and multiple vectors is very inefficient and a very poor use of MATLAB):
a = [1,2,3,4,5;4,5,7,8,9];
b = [6,7,8,9,10;3,2,4,5,7];
c = a+b
c = 2×5
7 9 11 13 15 7 7 11 13 16

More Answers (0)

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!