Add from different array's using for loop

1 次查看(过去 30 天)
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 个评论
wytze van der Zee
wytze van der Zee 2020-6-27
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

请先登录,再进行评论。

回答(1 个)

madhan ravi
madhan ravi 2020-6-27
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{:});

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by