2

I am trying to find a way to make two lists the same length. How can I add zeros to one list so as to make it have the same length with the first one?

i.e. list1=[ 1 2 3 4 5]; list2=[ 1 2 3]

3 Answers 3

3

There are many ways you can do that. One of them is

list3 = zeros(size(list1)); %# create an array of the same shape as list1
list3(1:numel(list2)) = list2(:); %# fill in the elements defined in list2

Another way is

list3 = [list2, zeros(1,length(list1)-length(list2))];

Both of these ways assume that list2 is shorter than list1.

2

Here's a one-liner for the case where you know list2 is shorter than list1

list2(numel(list1)) = 0;
1

Assuming that you do not know which of the two lists is bigger. You can do the following:

dif = size(l2)-size(l1);

if dif(2) < 0
    l2 = [l2, zeros(1, -dif(2))];
else
    l1 = [l1, zeros(1, dif(2))];
end

(This works on octave)

l1 = list1
l2 = list2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.