将数据从文件复制到结构中

时间:2015-03-23 04:27:25

标签: matlab struct

我需要帮助设计一个数据结构来存储文件中的风暴数据。我将使用这些字段名称:代码,数量,持续时间和强度。强度是降雨量除以持续时间。(我应该怎么做以计算强度?)我将数据加载到变量" mydata",然后将我的数据复制到结构矢量中叫" vecdata"。

我的最终结构向量应该与数据文件中的行数具有相同数量的元素。另外,它应该有4个字段,上面有我提到的字段名称。

% Creating an example data file 
anum = randi([3,10]);
thedata = [randi([1,350],anum,1),rand(anum,1)*5,rand(anum,1)*15];
save mydata.dat thedata -ascii
clear

%  loaded the data using the load function into "mydata":
mydata = load('mydata.dat') 

% Tried to copy the data from "mydata" into a vector of structures called "vecdata":

vecdata = [struct('code','amount','duration','intensity')];

这是一个非常普遍的问题。如何从上面的文件中复制数据? mydata的行必须与vecdata中的元素数匹配。我该如何检查?

1 个答案:

答案 0 :(得分:0)

%first of all, calculate the missing intensity
mydata(:,end+1)=mydata(:,3)./mydata(:,2);
%define the fieldnames for your struct
labels={'code','amount','duration','intensity'};
%there is no array2struct, so we convert to cell first and use cell2struct.
cell2struct(num2cell(mydata),labels,2)