问题描述
假设我们有一个数据,这个单元阵列:
Suppose that we have this cell array of data :
a={43 432 2006;
254 12 2008;
65 35 2000;
64 34 2000;
23 23 2006;
64 2 2010;
32 5 2006;
22 2 2010}
本单元阵列的最后一列是年。我想根据多年这样的分类数据(行):
Last column of this cell array is years. I want classify data(rows) based on years like this :
a_2006 = {43 432 2006;
32 5 2006;
32 5 2006}
a_2008 = {254 12 2008};
a_2000 = {65 35 2000;
64 34 2000}
a_2010 = {64 2 2010;
22 2 2010}
我有三列不同年份的每一个单元阵列中(该单元阵列是一个示例),所以我要自动的方法来确定这些年来,并将其分类为 a_yearA
, a_yearB
等,或其他的命名,我可以分辨年,具有多年轻易下codeS呼叫数据。
I have different years in column three in every cell array (this cell array is a sample) so I want an automatic method to determine the years and classify them to a_yearA
, a_yearB
etc. or other naming that I can distinguish years and call data with years easily in following codes.
我怎样才能做到这一点?
How can I do this?
Thanks.da
Thanks.da
推荐答案
EVAL这里不建议报告。我建议将其保存在一个结构阵列像
eval is not recommanded here. I would suggest to save it in a struct array like that
a={43 432 2006;
254 12 2008;
65 35 2000;
64 34 2000;
23 23 2006;
64 2 2010;
32 5 2006;
22 2 2010};
tmp = cell2mat(a);
% clear a or take another variable name for your struct to prevent warnings
clear a
years=unique(tmp(:,3));
for n = 1:numel(years)
a.(['a_' num2str(years(n))])=tmp(tmp(:,3)==years(n),:);
end
看起来像
>> a
a =
a_2000: [2x3 double]
a_2006: [3x3 double]
a_2008: [254 12 2008]
a_2010: [2x3 double]
>> a.a_2000
ans =
65 35 2000
64 34 2000
此外,你可以轻松地访问您的结构数组再次循环(你不能做这样容易与EVAL黑客)。
Furthermore, you can easily access your struct arrays in a loop again (what you can't do such easy with the eval hack).
>> names=fieldnames(a)
names =
'a_2000'
'a_2006'
'a_2008'
'a_2010'
>> for n = 1:numel(names)
a.(names{n})
end
在电池串
更新
好了,说有串在你的细胞
update with strings in cell
Well, say there are strings in your cell
a={'43' '432' 2006;
'254' '12' 2008;
'65' '35' 2000;
'64' '34' 2000;
'23' '23' 2006;
'64' '2' 2010;
'32' '5' 2006;
'22' '2' 2010};
% save original variable 'a' for accessing later
tmp.cell = a;
% save just the years in a matrix for more easy accessing + we need the
% indizes for getting the values from the cell later in the loop
tmp.years = cell2mat(a(:,3));
% clear variable a or take another variable name for your struct to prevent warnings
clear a
% get unique years for iteration
tmp.unique_years=unique(tmp.years);
for n = 1:numel(tmp.unique_years)
a.(['a_' num2str(tmp.unique_years(n))])=tmp.cell(tmp.years==tmp.unique_years(n),:);
end
的结果是一样的,但你的结构现在细胞
The result is the same, but your structs are now cells
>> a
a =
a_2000: {2x3 cell}
a_2006: {3x3 cell}
a_2008: {'254' '12' [2008]}
a_2010: {2x3 cell}
这篇关于划入基于MATLAB年的数据(单元阵列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!