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

2 views (last 30 days)
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

Answers (2)

Matt J
Matt J on 12 Oct 2020
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 on 12 Oct 2020
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!