How to make vectors zero when adding two different size vectors?

16 ビュー (過去 30 日間)
Kenny Dang
Kenny Dang 2017 年 1 月 30 日
編集済み: Stephen23 2017 年 1 月 30 日
I know how to make vectors add such as x=[1 2 3] and y=[-1 2 -1] and it should return as [0 4 2] But when adding two different length vectors such as x=[1 2 3 4 5] and y=[-1 -2 3[], then y should first be transformer to [0 0 -1 -2 3] and the function returns as [1 2 2 2
function y = adding(a,b)
if length(a) == length(b), y=b+a; end
if length(a) < length(b), y=a+ zeros(1,length(a)-length(b)); end
if length (a) > length(b), y=b+ zeros(1,length(b)-length(a)); end
end

採用された回答

Stephen23
Stephen23 2017 年 1 月 30 日
編集済み: Stephen23 2017 年 1 月 30 日
function Z = adding(A,B)
d = numel(A)-numel(B);
Z = [zeros(1,-d),A] + [zeros(1,d),B];
end
and tested:
>> adding([1,2,3,4,5],[-1,-2,3])
ans =
1 2 2 2 8

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by