在矩阵中保存不同大小的向量

时间:2016-06-23 08:19:24

标签: matlab for-loop matrix vector

我想在许多向量中划分一个向量,并将它们全部放在矩阵中。我收到此错误"订阅分配维度不匹配。"

STEP = zeros(50,1);
STEPS = zeros(50,length(locate));
for i = 1:(length(locate)-1)
    STEP = filtered(locate(i):locate(i+1));
    STEPS(:,i) = STEP;
end

我取值"过滤"例如,从(1:50)开始,我希望将它存储在矩阵的第一行,然后对于迭代2,我取值"从(50:70)过滤,例如我把它存放在矩阵的第2行,直到循环结束..

如果有人有想法,我就无法得到它!谢谢!

1 个答案:

答案 0 :(得分:2)

如评论中所述,要使其工作,您可以使用 -

编辑最后的循环代码
STEPS(1:numel(STEP),i) = STEP;

此外,输出数组STEPS似乎不使用最后一列。因此,初始化可以使用少一列,如此 -

STEPS = zeros(50,length(locate)-1);

循环代码一切都很好,但从长远来看,使用像MATLAB这样的高级语言,你可能想要寻找更快的代码,并且有一种方法可以实现矢量化代码。所以,让我建议使用bsxfun的屏蔽功能来处理这样的 ragged-arrays 的矢量化解决方案。涵盖locate中的通用元素的实现看起来像这样 -

% Get differentiation, which represent the interval lengths for each col
diffs = diff(locate)+1;

% Initialize output array
out = zeros(max(diffs),length(locate)-1);

% Get elements from filtered array for setting into o/p array
vals = filtered(sort([locate(1):locate(end) locate(2:end-1)]));

% Use bsxfun to create a mask that are to be set in o/p array and set thereafter
out(bsxfun(@ge,diffs,(1:max(diffs)).')) = vals;

运行样本以进行验证 -

>> % Inputs
locate = [6,50,70,82];
filtered = randi(9,1,120);

% Get extent of output array for number of rows
N = max(diff(locate))+1;

>> % Original code with corrections
STEP = zeros(N,1);
STEPS = zeros(N,length(locate)-1);
for i = 1:(length(locate)-1)
    STEP = filtered(locate(i):locate(i+1));
    STEPS(1:numel(STEP),i) = STEP;
end

>> % Proposed code
diffs = diff(locate)+1;
out = zeros(max(diffs),length(locate)-1);
vals = filtered(sort([locate(1):locate(end) locate(2:end-1)]));
out(bsxfun(@ge,diffs,(1:max(diffs)).')) = vals;

>> max_error = max(abs(out(:)-STEPS(:)))
max_error =
     0