Adding two row arrays that are different lengths
20 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(4 个)
Sean de Wolski
2014-10-17
编辑:Sean de Wolski
2014-10-17
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)
0 个评论
Star Strider
2014-10-17
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’.
0 个评论
Kelly Kearney
2014-10-17
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
0 个评论
Azmat Ameen
2020-12-17
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!