How to read numeric data with different number of columns

조회 수: 8 (최근 30일)
Jon
Jon 2025년 1월 29일
댓글: Jon 2025년 1월 30일
I would like to read in the numeric data below into 3 different arrays:
0 0.2 0.5 0.8 into "a_on_t"
4 10 into "Ri_on_t" and
2 5 10 into "2c_on_a"
I code just hard code these in, but it would be better to read them from a file. I was thinking of constructing the file like so:
% Header info describing file contents
% Rows correspond to:
% a / t
% Ri / t
% 2c / a
0 0.2 0.5 0.8
4 10
2 5 10
or, alternatively:
% Header info describing file contents
a_on_t 0 0.2 0.5 0.8
Ri_on_t 4 10
2c_on_a 2 5 10
I would like to be able to extract the names of the arrays in which to store the data from the file and, of course, to extract the numbers from the file. As I am using R2018a I don't have access to the table reading functions. I have tried putting the data into a cell using textscan, but I just end up with a list (or 1D array) of numbers. I definitely need the numbers, I could hard code the names of the arrays for now.
fgetl might be a possibility, but then there is the difficulty of extracting the data from a cell and converting characters to numbers.
Am I missing something obvious? This seems much more difficult than it should be.
Thanks!
  댓글 수: 4
Jon
Jon 2025년 1월 30일
@Stephen23. Thanks for the link about naming of variables. I have bookmarked this and intend to read it when we have a rainy day and I have a bit of spare time. Looks like a pretty contentious subject! Nor have I ever really understood the eval command, so hope to learn something new.
regards
Jon

댓글을 달려면 로그인하십시오.

채택된 답변

Adam Danz
Adam Danz 2025년 1월 29일
편집: Adam Danz 2025년 1월 29일
Is this what you are looking for?
file = "data.txt";
t = readtable(file, 'ReadRowNames',true,"Delimiter",'\t')
t = 3x4 table
Var1 Var2 Var3 Var4 ____ ____ ____ ____ a_on_t 0 0.2 0.5 0.8 Ri_on_t 4 10 NaN NaN 2c_on_a 2 5 10 NaN
The data file contains comment lines that begin with "%", contains row names, and is tab delimited.
% Header info describing file contents
a_on_t 0 0.2 0.5 0.8
Ri_on_t 4 10
c_on_a 2 5 10
  댓글 수: 1
Jon
Jon 2025년 1월 30일
Hi Adam. After discovering that readtable was, in fact, available, I came up with something similar, but I re-arranged my input data into columns and used "ReadVariableNames". I prefer your solution where you have used "readrownames", which I was unaware of - it makes the input file easier to read.
Thanks for your help.
Jon

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by