Reputation: 3389
I have to add multiple arrays together in a for loop and the arrays will very in size so sometimes I will need to pad for the array x and sometimes I will need to pad for the array y how can I have the arrays padded dynamically?
I know how to pad manually (see code below) but how can I do it dynamically if the size of the array x or the size of the array y will vary?
x = [1 2 3 4 5 6]'
y = [3 5 7 8]';
A = x + [y;zeros(2,1)];
This will result in A = [4 7 10 12 5 6]'
PS: I'm using octave 3.8.1 with is like matlab
Upvotes: 1
Views: 3281
Reputation: 1931
Actually, you do not have to pad the arrays in order to add them. You can do something like:
% Just some random arrays
A = rand(1, 10);
B = rand(1, round(rand(1,1)*10)+1);
% Then add them
if length(A) < length(B), C = A + B(1:length(A));
else C = B + A(1:length(B));
% Or...
C = A(1:max(length(A), length(B))) + B(1:max(length(A), length(B)));
What I suggest is just use the elements that matters. This means that you do not have to add zeros in the array but just add all the elements of the short vector with the same amount of elements from the larger vector.
The only reason to zero-pad the vectors is to make use of the sum()
function of MATLAB for an array of NxM dimensions.
Upvotes: 1
Reputation: 9864
Find the max length and pad both of them by the difference.
L = max(length(x), length(y));
A = [x; zeros(L-length(x),1)] + [y; zeros(L-length(y),1)];
It can easily be extended to more than two vectors:
L = max(length(x), length(y), length(z));
A = [x; zeros(L-length(x),1)] + [y; zeros(L-length(y),1)] + [z; zeros(L-length(z),1)];
Upvotes: 3
Reputation: 18177
x = [1 2 3 4 5 6]'
y = [3 5 7 8]';
L1 = length(x);
L2 = length(y);
if L1>L2
A = x + [y;zeros(L1-L2,1)];
elseif L2>L1
A = x + [y;zeros(L2-L1,1)];
else
A = x + y;
end
This should check the lengths of both arrays and pad the smaller one to the size of the larger one.
Upvotes: 0