MATLAB function adds two nonnegative integers where x has at least as many digits as y

조회 수: 1 (최근 30일)
My task is to write a MATLAB function that adds two nonnegative integers, assuming that x has at least as many digits as y. x,y, and x_plus_y are row vectors representing nonnegative integers. Each element of the vectors stores one digit of a nonnegative integer. (12345 is represented by [1 2 3 4 5]). I need assistance in storing these numbers as vectors as I am lost on how to do so.
Here is what I have so far, and I apologize that it is not much.
function x_plus_y = hw24(x,y)
%
x = zeros(size(x));
y = zeros(size(y));
x_plus_y = zeros(size(x,y));
for k = 1:length(x)
for k = 1:length(y)
x_plus_y = x(k) + y(k);
end
end

답변 (2개)

Matt J
Matt J 2020년 10월 12일
Hint: You can convert from vector form to a single number as follows
x=[1 2 3 4 5];
xx=x*10.^(4:-1:0).'
xx = 12345

Ameer Hamza
Ameer Hamza 2020년 10월 12일
Check this alternate method
function x_plus_y = hw24(x,y)
nx = numel(x);
ny = numel(y);
n = max(nx, ny);
x_plus_y = zeros(1, n+1);
x_plus_y = x_plus_y + [zeros(1,n-nx+1) x];
x_plus_y = x_plus_y + [zeros(1,n-ny+1) y];
x_plus_y = mod(x_plus_y,10) + [floor(x_plus_y(2:end)/10) 0];
end
Result
>> x = [9 9 9 9 9];
>> y = [8 6 3 1 9];
>> z = hw24(x, y)
z =
1 8 6 3 1 8

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by