如何将数组分成矩阵中的不同行(Matlab) [英] How can I separate an array into different rows in a matrix (Matlab)
问题描述
我正在尝试使用For循环(或实际上任何有效的形式)构造一个NaN矩阵,该矩阵的一部分包含行作为数组
I am trying to construct a NaN matrix that has parts of an array as its rows using For Loops (or really any form that works)
例如:
W = [0 0 0 2 3 2 0 0 4 5 6 6 5 0 0 0 0 8 8 9 8 0 0 0 0 ... ]
每当由零引起的刹车时,我只想迭代数字而不迭代零,以使每当有数字再次被零分隔时,每次都会在我的新矩阵中形成新的一行,结果是:
whenever there is a brake caused by the zeros I want to iterate only the numbers and not the zeros in such that whenever there are numbers again separated by zeroes it forms a new row each time in my new matrix, resulting in:
Matrix = NaN(5) %just big enough to fit everything
Matrix = [2 3 2 NaN NaN; 4 5 6 6 5;8 8 9 8 NaN] % and so forth
*我一直为此使用Nested For Loop,但仍然遇到错误. 预先谢谢你!
*I've been using a Nested For Loop for this but still getting errors. Thank you in advance!
推荐答案
这是不使用循环的解决方案.
Here is a solution without using loops.
W = [0 0 0 2 3 2 0 0 4 5 6 6 5 0 0 0 0 8 8 9 8 0 0 0 0];
W_idx = logical(W);
lbl = cumsum([diff([false W_idx]) > 0]) .* W_idx;
%lbl = bwlabel(W_idx) %use the image processing toolbox
count = accumarray(lbl(:)+1,1).';
count = count(2:end);
result_idx = (1:max(count)).' <= count ;
result = NaN(size(result_idx));
result(result_idx) = W(W_idx);
result = result.';
结果:
result =
2 3 2 NaN NaN
4 5 6 6 5
8 8 9 8 NaN
如果您需要数字索引,则可以为时间索引创建一个单独的数组:
If you need indices of numbers you can create a separate array for the time indices:
time_data = 1:25;
time_result = NaN(size(result_idx));
time_result(result_idx) = time_data(W_idx);
time_result = time_result.';
这篇关于如何将数组分成矩阵中的不同行(Matlab)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!