简体   繁体   中英

How to create a structure with fields from an array of strings in matlab?

I have the following code, I'm trying to create an structure with field names from the cellarray of string.

data1 has the following data, it's a 5x4:

1   5    298      53
2   9    284      35
3   0    582      329
4   17   892      67
45  183  45       29

data1 = xlsread('data1.xlsx');
namesoftags = {'timeaxis','cputime','flux','volts'};
for i =1:4
    S = cell2struct(data1(:,i),namesoftags(i));
end

But it's giving this error:

Error using cell2struct
Unknown command option.

Error in structuredemo (line 4)
    S = cell2struct(data1(:,i),namesoftags(i));

Thank you.

You a providing a matrix data1(:,i) , rather than a cell, to the cell2struct function. However, you don't need this function to accomplish your goal here. Use S.(fieldname) to build your structure instead.

data1 = xlsread('data1.xlsx');
namesoftags = {'timeaxis','cputime','flux','volts'};
for i =1:4
    S.(namesoftags{i}) = data1(:,i);
end

S = 

  struct with fields:

    timeaxis: [5×1 double]
     cputime: [5×1 double]
        flux: [5×1 double]
       volts: [5×1 double]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM