Compare vectors of different lengths using end of shorter one when it ends
3 views (last 30 days)
Show older comments
Say I have three vectors:
A = 1:10;
B = 1:5;
C = 1:15;
I want to do an operation using A and either B or C, but, when the shorter vector ends, I want to continue the operation using the last value of the shorter one until the longer one ends too. For example, if I want to add them:
A+B = [1+1,2+2,3+3,4+4,5+5,6+5,7+5,8+5,9+5,10+5];
A+C = [1+1,2+2,3+3,4+4,5+5,6+6,7+7,8+8,9+9,10+10,10+11,10+12,10+13,10+14,10+15];
How can I do this efficiently? Note that A is not always the shortest, so I need to identify which one is shorter as part of this. Thanks!
0 Comments
Accepted Answer
Scott MacKenzie
on 3 May 2023
Someting like this perhaps:
A = 1:10;
B = 1:5;
C = 1:15;
nA = length(A);
nB = length(B);
nC = length(C);
% A + B
if nA < nB
[A repelem(A(end),1,nB-nA)] + B
else
A + [B repelem(B(end),1,nA-nB)]
end
% A + C
if nA < nC
[A repelem(A(end),1,nC-nA)] + C
else
A + [C repelem(C(end),1,nA-nC)]
end
2 Comments
Scott MacKenzie
on 4 May 2023
Edited: Scott MacKenzie
on 4 May 2023
If the vectors are in a cell array (CA), then something like this would work:
A = 1:10;
B = 1:5;
C = 1:15;
CA = {A; B; C}
nA = length(CA{1});
nB = length(CA{2});
nC = length(CA{3});
% A + B
if nA < nB
[CA{1} repelem(CA{1,end},1,nB-nA)] + CA{2}
else
CA{1} + [CA{2} repelem(CA{2}(end),1,nA-nB)]
end
% A + C
if nA < nC
[CA{1} repelem(CA{1}(end),1,nC-nA)] + CA{3}
else
CA{1} + [CA{3} repelem(CA{3}(end),1,nA-nC)]
end
If there are lots of vectors in CA, you could build a loop that includes the logic above to add the elements in the first vector to the elements in each subsequent vector in the cell array.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!