在MATLAB“数组的数组”? [英] 'Array of arrays' in matlab?

查看:126
本文介绍了在MATLAB“数组的数组”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哎,有麻烦一丁点儿。试图分配一个可变长度的一维数组到一个数组,例如不同的值。

Hey, having a wee bit of trouble. Trying to assign a variable length 1d array to different values of an array, e.g.

a(1) = [1, 0.13,0.52,0.3];
a(2) = [1, 0, .268];

不过,我得到的错误:

However, I get the error:

???  In an assignment  A(I) = B, the number of elements in B and
 I must be the same.

Error in ==> lab2 at 15
a(1) = [1, 0.13,0.52,0.3];

我presume这意味着该公司预计,标值,而不是数组。是否有人知道如何给数组分配给这个值?

I presume this means that it's expecting a scalar value instead of an array. Does anybody know how to assign the array to this value?

我宁愿不直接把它定义为一个二维数组,因为它是在一个循环

I'd rather not define it directly as a 2d array as it is for are doing solutions to different problems in a loop

编辑:!明白了

一个(1,1:4)= [1,0.13,0.52,0.3];

a(1,1:4) = [1, 0.13,0.52,0.3];

一个(2,1:3)= [1,0,0.268];

a(2,1:3) = [1, 0, .268];

推荐答案

什么你可能想写了。

a(1,:) = [1, 0.13,0.52,0.3];
a(2,:) = [1, 0, .268];

即第一行是 [1,0.13,0.52,0.3] ,第二行是 [1,0,0.268] 。这是不可能的,因为这将是一(2,4)的值

i.e the the first row is [1, 0.13,0.52,0.3] and the second row is [1, 0, .268]. This is not possible, because what would be the value of a(2,4) ?

有两种方法来解决这个问题。

There are two ways to fix the problem.

(1)使用电池阵列

a{1} = [1, 0.13,0.52,0.3];
a{2} = [1, 0, .268];

(2)如果你知道列的最大可能数您的解决方案都会有,你可以preallocate阵列,并在结果像这样写的(如果你不这样做preallocate,你会
获得零填充。您还冒险放慢你的循环很多,如果有多次迭代,因为数组将在每次迭代重新创建。

(2) If you know the maximum possible number of columns your solutions will have, you can preallocate your array, and write in the results like so (if you don't preallocate, you'll get zero-padding. You also risk slowing down your loop a lot, if there are many iterations, because the array will have to be recreated at every iteration.

a = NaN(nIterations,maxNumCols); %# this fills the array with not-a-numbers

tmp = [1, 0.13,0.52,0.3];
a(1,1:length(tmp)) = tmp;
tmp = [1, 0, .268];
a(2,1:length(tmp)) = tmp;

这篇关于在MATLAB“数组的数组”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆