Compare vectors of different lengths using end of shorter one when it ends
2 次查看(过去 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!