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

조회 수: 3 (최근 30일)
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!

채택된 답변

Scott MacKenzie
Scott MacKenzie 2023년 5월 3일
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
Dan Houck
Dan Houck 2023년 5월 3일
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 2023년 5월 4일
편집: Scott MacKenzie 2023년 5월 4일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by