开发者

Adding zeros to a list

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]


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.


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

list2(numel(list1)) = 0;


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜