【问题标题】:Copy a data from a file into a structure将文件中的数据复制到结构中
【发布时间】:2015-03-23 04:27:25
【问题描述】:

我需要帮助设计一个数据结构来存储文件中的风暴数据。我将使用这些字段名称:代码、数量、持续时间和强度。强度是降雨量除以持续时间。(我应该怎么做才能计算强度?)我将数据加载到变量“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 中的元素数相匹配。如何检查?

【问题讨论】:

  • 请清理代码,每行包含两次。结构应该如何?您的数据有三列,但您的结构有四个字段?还是你想要一个带有字段名的 anum 的空结构?
  • 强度场是数量除以持续时间,结构应该有适当的值。
  • 您的代码仍然包含一些重复的行和'。对于以后的问题,只需用一个标签缩进您的完整代码,它就会正确显示。

标签: matlab struct


【解决方案1】:
%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)

【讨论】:

    猜你喜欢
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2020-10-22
    相关资源
    最近更新 更多