Adding two row arrays that are different lengths

50 views (last 30 days)
I have to write a function to add two row arrays together for any large number as if you were adding them on a calculator. I can't get them to add if they aren't the same length as it says 'Matrix dimensions must agree'. I know you need to use the zeros function but I can't figure it out. e.g. i have to make [1,2,3,4,5] + [1,2,3] go to [1,2,3,4,5] +[0,0,1,2,3]
Also how to you make the remainder go onto the next number e.g.: [2,3,4,5] + [2,3,4,5] = 4 6 9 0 instead of 4 6 8 10??
Any help would be great!

Answers (4)

Sean de Wolski
Sean de Wolski on 17 Oct 2014
Edited: Sean de Wolski on 17 Oct 2014
The first one:
x = [1 2 3 4 5]
y = [1 2 3]
z = x+padarray(y,[0, numel(x)-numel(y)],0,'pre')
The second:
x = 2:5
y = 2:5
z = mod(x+y,10)

Star Strider
Star Strider on 17 Oct 2014
This works:
First part:
a1 = [1 2 3 4 5];
a2 = [1 2 3];
a2ix = (1+length(a1)-length(a2)):length(a1);
a2(a2ix) = a2;
a2(1:a2ix(1)-1) = zeros(1,a2ix(1)-1);
Output for the first part: ‘a1’ and ‘a2’.
Second part:
b1 = [2 3 4 5];
b2 = [2 3 4 5];
c = 0; % Initial Carry = 0
for k1 = length(b1):-1:1
b3(k1) = b1(k1)+b2(k1)+c; % Add + Carry
c = fix(b3(k1)/10); % Generate Carry
b3(k1) = b3(k1)-(c*10); % Subtract 10*Carry
end
Output for the second part: ‘b3’.

Kelly Kearney
Kelly Kearney on 17 Oct 2014
Wouldn't it be easier to just convert your arrays to single numbers and add?
array2num = @(x) sum(10.^(length(x)-1:-1:0) .* x);
num2array = @(x) str2num(num2str(x)')';
x = [1 2 3 4 5];
y = [1 2 3];
num2array(array2num(x) + array2num(y))
ans =
1 2 4 6 8
x = [2 3 4 5];
y = [2 3 4 5];
num2array(array2num(x) + array2num(y))
ans =
4 6 9 0

Azmat Ameen
Azmat Ameen on 17 Dec 2020
function[t,x]=padding(t1,t2,x1,x2)
t=min(min(t1),min(t2)):max(max(t1),max(t2));
y1=zeros(1,length(t));
y2=y1;
y1((t>=min(t1))&(t<=max(t1)))=x1;
y2((t>=min(t2))&(t<=max(t2)))=x2;
x=(y1+y2)
stem(t,x)
end
Use this function to pad zeros and you will get the addition of two different array with different length.

Categories

Find more on Creating and Concatenating Matrices 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!