将零添加到列表中

发布于 2024-11-01 18:52:05 字数 97 浏览 2 评论 0原文

我正在尝试找到一种方法使两个列表的长度相同。如何向一个列表添加零以使其与第一个列表具有相同的长度?

即list1=[ 1 2 3 4 5];列表2=[ 1 2 3]

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]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

中二柚 2024-11-08 18:52:05

有很多方法可以做到这一点。其中一种是

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

另一种方法是

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

这两种方法都假设list2list1短。

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.

你的往事 2024-11-08 18:52:05

这是针对您知道 list2 比 list1 短的情况的单行代码

list2(numel(list1)) = 0;

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

list2(numel(list1)) = 0;
缱倦旧时光 2024-11-08 18:52:05

假设您不知道两个列表中哪一个更大。您可以执行以下操作:(

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

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

这适用于八度)

l1 = list1
l2 = list2

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文