# Loop on two matrices

30 views (last 30 days)
Tarek on 2 Feb 2021
Edited: Jan on 2 Feb 2021
I have these two matrices:
TL=[ 21;36;31;8;34;22;14;34;4;51]
TTB=[207;92;133;1;99;1;127;197;228;42]
I want to create a vector that takes eache value of TTB ans repeat it for Tl(i) time; also each time it should ad a +1.
for exemple: 207 should be added in a matrice lets name it A, 21 times as A(1)=207, A(2)=208, A(3)=209......A(21)=207+21
i hope it is clear ;
thank you
Jan on 2 Feb 2021
If A(1) is 207, A(21) should be 207 + 20, not +21.

Jan on 2 Feb 2021
Edited: Jan on 2 Feb 2021
TL = [ 21;36;31;8;34;22;14;34;4;51];
TTB = [207;92;133;1;99;1;127;197;228;42];
C = cell(1, numel(TL));
for k = 1:numel(TL)
C{k} = TTB(k) + (0:TL(k)-1);
end
Result = [C{:}];
[EDITED] A one-liner version:
Result = cell2mat(cellfun(@(a, b) a + (0:b-1), ...
num2cell(TTB), num2cell(TL), 'uniformoutput', 0).');
I'd prefer the loop, because it is easier to read.

VBBV on 2 Feb 2021
Edited: VBBV on 2 Feb 2021
clear
TTB = [207;92;133;1;99;1;127;197;228;42]
TL =[21;36;31;8;34;22;14;34;4;51]
i = 1;
for j = 1:length(TTB)
while i<=TL(j)
TX(j) = TTB(j)+ i; % desired matrix
i = i+1;
end
i = 1;
end
Tarek on 2 Feb 2021
yes this works very well with a small error where always for the second value in a set it is +2 instead of +1 (exemple 207, 209 (208 is being skipped)). but thank you for your time.