MatLab相对于第一列转换矩阵 [英] MatLab to convert a matrix with respect to 1st col
本文介绍了MatLab相对于第一列转换矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题是通过第一列索引将不同行中的值分组
如果
A = [2 3 234 ; 2 44 99999; 2 99999 99999; 3 123 99; 3 1232 45; 5 99999 57]
1st column | 2nd column | 3rd column
--------------------------------------
2 3 234
2 44 99999
2 99999 99999
3 123 99
3 1232 45
5 99999 57
我想做
1st col | 2nd col | 3rd col | 4th col | 5th col | 6th col| 7th col
--------------------------------------------------------------------
2 3 234 44
3 123 99 1232 45
5 57
也就是说,对于A的第1个列中的每个数字,我想输入除"99999"以外的数字
That is, for each numbers in the 1st col of A, I want to put numbers EXCEPT "99999"
如果我们忽略"99999除外"部分,则可以将代码编码为按第一列索引将不同行中的组值分组
If we disregard the "except 99999" part, we can code as Group values in different rows by their first-column index
[U, ix, iu] = unique(A(:,1));
vals = reshape(A(:, 2:end).', [], 1); %'// Columnize values
subs = reshape(iu(:, ones(size(A, 2) - 1, 1)).', [], 1); %'// Replicate indices
r = accumarray(subs, vals, [], @(x){x'});
但是显然,此代码不会忽略99999.
But obviously this code won't ignore 99999.
我想有两种方法
1. first make r, and then remove 99999
2. remove 99999 first, and then make r
无论如何,我只想快一点.
Whichever, I just want faster one.
提前谢谢!
推荐答案
我认为选项1更好,即先设为r,然后删除99999 .有了r,您可以按以下方式删除99999:
I think options 1 is better, i.e. first make r, and then remove 99999. Having r, u can remove 99999 as follows:
r2 = {}; % new cell array without 99999
for i = 1:numel(r)
rCell = r{i};
whereIs9999 = rCell == 99999;
rCell(whereIs9999) = []; % remove 99999
r2{i} = rCell;
end
或更花哨的方式:
r2= cellfun(@(c) {c(c~=99999)}, r);
这篇关于MatLab相对于第一列转换矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文