根据第一列中的数字拆分矩阵 [英] Split matrix based on number in first column
问题描述
我有一个矩阵,其格式如下:
I have a matrix which has the following form:
M =
[1 4 56 1;
1 3 5 1;
1 3 6 4;
2 3 5 0;
2 0 0 0;
3 1 2 3;
3 3 3 3]
我想根据第一列中给出的数字拆分此矩阵.所以我想将矩阵拆分成这样:
I want to split this matrix based on the number given in the first column. So I want to split the matrix into this:
A =
[1 4 56 1;
1 3 5 1;
1 3 6 4]
B =
[2 3 5 0;
2 0 0 0]
C =
[3 1 2 3;
3 3 3 3]
我通过以下循环进行了尝试,但这为我提供了所需的矩阵(带有零行):
I tried this by making the following loop, but this gave me the desired matrices with rows of zeros:
for i = 1:length(M)
if (M(i,1) == 1)
A(i,:) = M(i,:);
elseif (M(i,1) == 2)
B(i,:) = M(i,:);
elseif (M(i,1) == 3)
C(i,:) = M(i,:);
end
end
则矩阵C的结果例如为:
The result for matrix C is then for example:
C =
[0 0 0 0;
0 0 0 0;
0 0 0 0;
2 3 5 0;
2 0 0 0]
我应该如何解决这个问题?
How should I solve this issue?
其他信息:
实际数据的第一列中的日期为yyyymmdd
格式.该数据集跨越数年,我想将此数据集分解为每年的矩阵,然后将其分解为每个月的矩阵.
Additional information:
The actual data has a date in the first column in the form yyyymmdd
. The data set spans several years and I want to split this dataset in matrices for each year and after that for each month.
推荐答案
您可以使用 arrayfun
解决此任务:
You can use arrayfun
to solve this task:
M = [
1 4 56 1;
1 3 5 1;
1 3 6 4;
2 3 5 0;
2 0 0 0;
3 1 2 3;
3 3 3 3]
A = arrayfun(@(x) M(M(:,1) == x, :), unique(M(:,1)), 'uniformoutput', false)
结果A
是一个单元格数组,可以按以下方式访问其内容:
The result A
is a cell array and its contents can be accessed as follows:
>> a{1}
ans =
1 4 56 1
1 3 5 1
1 3 6 4
>> a{2}
ans =
2 3 5 0
2 0 0 0
>> a{3}
ans =
3 1 2 3
3 3 3 3
要在第一列中基于yyyymmdd格式拆分数据,可以使用以下命令:
To split the data based on an yyyymmdd format in the first column, you can use the following:
yearly = arrayfun(@(x) M(floor(M(:,1)/10000) == x, :), unique(floor(M(:,1)/10000)), 'uniformoutput', false)
monthly = arrayfun(@(x) M(floor(M(:,1)/100) == x, :), unique(floor(M(:,1)/100)), 'uniformoutput', false)
这篇关于根据第一列中的数字拆分矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!