Chen Xing
Chen Xing

Reputation: 7

How to extract data from a complex mat and save them to multiply tables

I am new to Matlab.

I want to save a mat to table files. I have a mat file like this. There is 1* 55 struct, which was stored in “data” field. the data structure of the table

I want to save the “track” field in these structs. And my code:

data = load('G:/my_file.mat');
my_output_file = 'G:/my_output.txt'

for my_track_data = data.data.track
    writetable(my_track_data, my_output_file)
end

But there is a error:

Expected one output from a curly brace or dot indexing expression, but there 55 results.

by the way, I can see the Matlab displayed all the results when I type: ''' data.data.track '''

All the 55 tables in the "data.data.track"

I tried just save it without a loop:

my_track_data = data.data.track
writetable(my_track_data, my_output_file)

It only save just the first table.

Upvotes: 0

Views: 296

Answers (2)

Chen Xing
Chen Xing

Reputation: 7

data = load('G:/my_file.mat');

# the braces is very important. It can convert 'data.data.track' to cell type for looping
required_data={data.data.track};

for k = 1:length(required_data)
    my_output_file = ['G:/test_' num2str(k) '.txt'];
    temp = requireddata(k);
    tt = cell2table(temp);
    writetable(tt.temp{1, 1}, my_output_file);
end


Upvotes: -1

nonDucor
nonDucor

Reputation: 2093

Matlab loops do not work as Python loops (i.e. they do not request an iterator from the structure). Therefore, you should use traditional indexing:

for i = 1:numel(data.data)
    my_data = data.data(i);
    writetable(my_data.track, my_output_file)
end

(In fact, you can use the "iterator style", but the for iterates over columns, not rows, so the results end up being dependent on the shape of your data and will most likely not be what you want).

Upvotes: 0

Related Questions