Add from different array's using for loop

1 view (last 30 days)
Hello,
I am sure the questen has been asked before but my search didn't result in a clear answer.
I have 2 array's (A and B). A = 1x120 double and B = 1x90 double
I would like to fill C with the first 40 elements of A, than the first 30 elements of B and so on.
I found out the underneath code works
C = [ A(1:40), B(1:30), A(41:80), B(31:60) etc.
However, the number of times I need to repeat this is variable (in this example A exists of 120 and B of 90, but sometimes A exists of 80 or 160 and B of 60 or 120).
Can anyone help me out with putting this into a for loop so the number of repeating depends on X?
  2 Comments
madhan ravi
madhan ravi on 27 Jun 2020
What did you try for your homework?
wytze van der Zee
wytze van der Zee on 27 Jun 2020
I tried
var1 = 40
var2 = 30
for x = 1:I
C = [A(((var1*(I-1))+1):var1*I), B(((var2*(I-1))+1):var2*I)]
But this overwrites the previous ones

Sign in to comment.

Answers (1)

madhan ravi
madhan ravi on 27 Jun 2020
Aix = [0, 40:40:120]; ; %120 is numel(A)
Bix = [0, 30:30:90]; %90 is numel(B)
n = numel(Aix);
c = cell(n-1, 1);
assert(isequal(n, numel(Bix)), 'SizeS DiffeR')
for k = 1:n-1
c{k} = [A(Aix(k)+1):A(Aix(k+1)), B(Bix(k)+1:Bix(k+1))];
end
Wanted = cat(2, c{:});

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!