我想将一个向量分成许多向量,然后将它们全部放入一个矩阵中。我收到此错误“下标赋值维度不匹配。”
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) 中获取“filtered”的值,我想将它存储在矩阵的第一行,然后对于迭代 2,我从“filtered from”中获取值(50:70) 例如,我将其存储在矩阵的第 2 行中,直到循环结束..
如果有人有想法,我不明白!谢谢!
最佳答案
如评论中所述,要使其正常工作,您可以在末尾使用 - 编辑循环代码
STEPS(1:numel(STEP),i) = STEP;
此外,输出数组 STEPS
似乎没有使用最后一列。因此,初始化可以少使用一列,就像这样 -
STEPS = zeros(50,length(locate)-1);
循环代码一切都很好,但从长远来看,使用像 MATLAB 这样的高级语言,您可能想要寻找更快的代码,而实现这一目标的一种方法是矢量化代码。因此,让我建议使用 bsxfun
的矢量化解决方案处理此类参差不齐的数组 的屏蔽能力。在 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;
用于验证的 sample 运行 -
>> % 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
关于matlab - 在矩阵中保存不同大小的向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37985915/