How can I add two vectors of same length or different length using for-loops?

8 ビュー (過去 30 日間)
Sunil Kunjachan
Sunil Kunjachan 2017 年 3 月 7 日
回答済み: Sunil Kunjachan 2017 年 3 月 7 日
for example: x=[9 9 9 9];y=[9 9 9 9] The result should be as z=[1 9 9 9 8]. How can I write a code using for-loops or any other means. Greatly appreciate help
  2 件のコメント
KSSV
KSSV 2017 年 3 月 7 日
How x = [9 9 9 9], y = [9 9 9 9] becomes z = [1 9 9 9 8]? What is the logic?
Sunil Kunjachan
Sunil Kunjachan 2017 年 3 月 7 日
I mean direct addition from right to left. That is first 9+9=18. Then that 1 carry over to the next left position. There it 9+9+1=19.Again that 1 is carry over to the next left position and add. The result is 19998. Thanks for the reply

サインインしてコメントする。

採用された回答

Jan
Jan 2017 年 3 月 7 日
編集済み: Jan 2017 年 3 月 7 日
Using the string conversion is efficient as long as the input does not have more than 16 digits. For longer vectors the limited precision of double will crop the least significant digits. For an arbitrary number of digits:
function c = DigitsAdd(a, b)
% Author: Jan Simon, License: Creative Commons Attribution Share Alike 3.0
isrow = size(a, 2) > 1;
na = numel(a);
nb = numel(b);
a = [zeros(max(1, nb - na + 1), 1); a(:)]; % Pad with at least one zero
b = [zeros(max(1, na - nb + 1), 1); b(:)];
c = a + b; % Standard addition
carry = 0; % Shift the values above 10
for k = numel(c):-1:1
cc = c(k) + carry;
c(k) = rem(cc, 10);
carry = (cc - c(k)) / 10; % Must be integer
end
if c(1) == 0 % Crop leading zero
c = c(2:numel(c));
% If wanted crop all leading zeros:
% c = c(find(c, 1):numel(c));
end
if isrow % Reply a row vector if input "a" was one
c = c.';
end

その他の回答 (1 件)

Sunil Kunjachan
Sunil Kunjachan 2017 年 3 月 7 日
Thank you very much Jan.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by