Info

此问题已关闭。 请重新打开它进行编辑或回答。

How to create a structural array from a txt file?

1 次查看(过去 30 天)
Hello,
I am very new to MATLAB and I need help creating a structural array. I have a txt file that is large in quantity (it has data dating back to 2012) with a few columns. The txt file is difficult to navigate which is why I want to create a structural array on MATLAB to make it more organized and easier to find individual data. I am not really sure how to create a structutal array with that many fields. Thank you.
  1 个评论
dpb
dpb 2020-8-6
Not sure what you mean by a "structural array"? Do you mean an array of struct that each column becomes a field in the struct? If so, not sure it will really help you all that much to "navigate" but we don't know what you mean there, either, precisely.
How large is "large"? And what do you want/need to do with it?
I'd guess a table or timetable would be a good candidate with (I'm guessing here) that some of the variables may be prime candidates to be categorical and then one could do searching on them for the navigation...
Be a lot easier to try to make specific recommendations with a smattering of what the data are and more details about the use case...

回答(1 个)

Puru Kathuria
Puru Kathuria 2020-8-10
Hi,
I understand that you want to extract data from a txt file and further save it in a struct or a matrix. There are two ways mentioned below.
The following code snippet reads the data from a txt file and save it a matrix.
%data.txt contains 4 rows and 3 columns.
fileID = fopen('data.txt','r'); %accessing and reading the file named data.txt
formatSpec = '%d %f %d'; % format specifiers for different columns present in the data
sizeA = [3 Inf]; % size of the data, specified as [No of columns , No of rows]
A = fscanf(fileID,formatSpec,sizeA); %extracting the data
A = A'; % Transposing the data matrix
The following code snippet reads the data from a txt file and save it in a struct.
[col1,col2,col3] = textread('data.txt','%d %d %d'); % reading data and saving independent columns
dataStruct = struct; % initialising struct
dataStruct.col1 = col1;
dataStruct.col2 = col2;
dataStruct.col3 = col3;
The following links contains more information on different format specifiers, different file formats and a few examples.
  1. fscanf
  2. textread

此问题已关闭。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by