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!
댓글 수: 0
채택된 답변
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
% A + C
if nA < nC
[A repelem(A(end),1,nC-nA)] + C
else
A + [C repelem(C(end),1,nA-nC)]
end
댓글 수: 2
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}
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!