[英]save vectors of different sizes in matrix
I would like to divide a vector in many vectors and put all of them in a matrix. 我想在许多向量中划分一个向量,并将它们全部放在矩阵中。 I got this error "Subscripted assignment dimension mismatch."
我收到此错误“订阅分配维度不匹配”。
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
I take the value of "filtered" from (1:50) at the first time for example and I would like to stock it in the first row of a matrix, then for iterations 2, I take value of "filtered from(50:70) for example and I stock it in row 2 in the matrix, and this until the end of the loop.. 我在第一次从(1:50)获取“过滤”的值,例如我想将它存储在矩阵的第一行,然后对于迭代2,我取值“过滤掉”(50: 70)例如,我将它存储在矩阵的第2行,直到循环结束。
If someone has an idea, I don't get it! 如果有人有想法,我不明白! Thank you!
谢谢!
As mentioned in the comments, to make it work you can edit the loopy code at the end with - 正如评论中所提到的,为了使它工作,您可以在最后编辑循环代码 -
STEPS(1:numel(STEP),i) = STEP;
Also, output array STEPS
doesn't seem to use the last column. 此外,输出数组
STEPS
似乎不使用最后一列。 So, the initialization could use one less column, like so - 因此,初始化可以使用少一列,如此 -
STEPS = zeros(50,length(locate)-1);
All is good with the loopy code, but in the long run with a high level language like MATLAB, you might want to look for faster codes and one way to achieve that would be vectorized codes. 循环代码一切都很好,但从长远来看,使用像MATLAB这样的高级语言,你可能想要寻找更快的代码,并且有一种方法可以实现矢量化代码。 So, let me suggest a vectorized solution using
bsxfun
's masking capability to process such ragged-arrays . 所以,让我建议使用
bsxfun
的屏蔽功能处理这种不规则数组的矢量化解决方案。 The implementation to cover generic elements in locate
would look something like this - 覆盖
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 run for verification - 样品运行验证 -
>> % 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.