我在MATLAB环境中工作,我有一些像这样的结构:
>> HTC_01
HTC_01 =
Name: 'HTC_One_M8-2015-02-11-15-40-30'
Date: '2015-02-11'
Time: [395768x1 double]
Ax: [395768x1 double]
Ay: [395768x1 double]
Az: [395768x1 double]
Lat: [395768x1 double]
Lon: [395768x1 double]
Quo: [395768x1 double]
Vel: [395768x1 double]
现在,我想从所有数组中选择一些数据,例如(4646:279745),并将输出放在一个与此名称相同的新数组中。
我想获得:
>> HTC_02 = my_resize(HTC_01, 4646, 279745)
HTC_02 =
Name: 'HTC_One_M8-2015-02-11-15-40-30'
Date: '2015-02-11'
Time: [275100x1 double]
Ax: [275100x1 double]
Ay: [275100x1 double]
Az: [275100x1 double]
Lat: [275100x1 double]
Lon: [275100x1 double]
Quo: [275100x1 double]
Vel: [275100x1 double]
问题是:我必须按数组做一个这样的数组,或者有一个更短的方法来做它?
在我看来,只调整数组在MATLAB中是非常简单的,所以必须存在一个简短的方法来做它而不创建函数。
答案 0 :(得分:1)
这将是一种方法 -
index_range = 4646:279745 %// index range
flds = {'Ax','Ay','Az','Lat','Lon','Quo','Vel'} %// fields to be selected
fnames = fieldnames(HTC_01) %// all fieldnames
%// Logical array with length as number of fields
%// and ones where the fields to be selected appear
idx = ismember(fnames,flds)
C = struct2cell(HTC_01) %// Get all of the data into a cell array
out1 = reshape([C{idx}],[],sum(idx)).' %//'#select fields
out2 = out1(:,index_range) %// select data from range
cell_out = mat2cell(out2,ones(1,size(out2,1)),size(out2,2))
%// Store truncated data into numeric fields and then save back as struct
C(idx) = cell_out
out = cell2struct(C,fnames,1)
答案 1 :(得分:1)
仅使用结构中的数组字段:
fields = fieldnames(HTC);
i = 1;
for x = 1:length(fields)
field = fields{x};
data = getfield(HTC,field);
if isa(data,'double')
output(:,i) = data(4646:279745);
i = i + 1;
end
end
所需的每个数据数组范围都保存为输出数组中的一列。
更新后更新:
function output = my_resize(input,r1,r2)
fields = fieldnames(input);
output = input;
for x = 1:length(fields)
field = fields{x};
data = getfield(input,field);
if isa(data,'double')
output = setfield(output,field,data(r1:r2,1));
end
end