Compare vectors of different lengths using end of shorter one when it ends

3 views (last 30 days)
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!

Accepted Answer

Scott MacKenzie
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
ans = 1×10
2 4 6 8 10 11 12 13 14 15
% A + C
if nA < nC
[A repelem(A(end),1,nC-nA)] + C
else
A + [C repelem(C(end),1,nA-nC)]
end
ans = 1×15
2 4 6 8 10 12 14 16 18 20 21 22 23 24 25
  2 Comments
Dan Houck
Dan Houck on 3 May 2023
I hadn't thought to replicate the last element to bring them up to the same length. How would you do this if you had a cell array of many vectors of different lengths and you want to loop through them?
Scott MacKenzie
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}
CA = 3×1 cell array
{[ 1 2 3 4 5 6 7 8 9 10]} {[ 1 2 3 4 5]} {[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]}
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
ans = 1×10
2 4 6 8 10 11 12 13 14 15
% 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
ans = 1×15
2 4 6 8 10 12 14 16 18 20 21 22 23 24 25
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!