I need to pass from a text file to a matrix in Matlab

1 回表示 (過去 30 日間)
Mark
Mark 2022 年 5 月 25 日
回答済み: Image Analyst 2022 年 5 月 26 日
I have the next .txt file.
Name-Goals-Assists-Red cards
Frank-6-2-0
Mike-0-5-4
Ben-23-11-2
I want to transform that into a matrix, for example named P. So that when I put P(1,2) I get 6 or P(3,1) I get Ben. First I use fopen to get the id but then I do not know how to do to have the matrix and not an array of cells.
  1 件のコメント
Stephen23
Stephen23 2022 年 5 月 26 日
"I do not know how to do to have the matrix and not an array of cells."
A mix of text and numeric cannot be stored in a numeric matrix.
Do not use a cell array, it just makes working with numeric data inefficient.
You should use a table, probably by using READTABLE when you import the data.

サインインしてコメントする。

採用された回答

Voss
Voss 2022 年 5 月 25 日
You say you want a matrix that contains stuff like the number 6 as well as the string "Ben" (or the character array 'Ben'). That's not possible to do with a matrix because each element of a matrix must be of the same class.
The closest you can get is to use a cell array, because the nice thing about cell arrays is that any element can be of any class.
P = {'Frank' 6 2 0; 'Mike' 0 5 4; 'Ben' 23 11 2} % cell array
P = 3×4 cell array
{'Frank'} {[ 6]} {[ 2]} {[0]} {'Mike' } {[ 0]} {[ 5]} {[4]} {'Ben' } {[23]} {[11]} {[2]}
P{1,2}
ans = 6
P{3,1}
ans = 'Ben'
P = ['Frank' 6 2 0; 'Mike' 0 5 4; 'Ben' 23 11 2] % trying to make a matrix doesn't work
Error using vertcat
Dimensions of arrays being concatenated are not consistent.

その他の回答 (2 件)

Image Analyst
Image Analyst 2022 年 5 月 25 日
After you read this:
attach the actual text file, or at least a part of it if it's too big.
In the meantime did you try
t = readtable(fileName); % Load into table.
P = table2array(t(:, 2:end)) % Convert columns 2 onwards into a matrix called P

Image Analyst
Image Analyst 2022 年 5 月 26 日
Or you could do this:
ca = {'Frank' 6 2 0; 'Mike' 0 5 4; 'Ben' 23 11 2} % Define a cell array
ca = 3×4 cell array
{'Frank'} {[ 6]} {[ 2]} {[0]} {'Mike' } {[ 0]} {[ 5]} {[4]} {'Ben' } {[23]} {[11]} {[2]}
%ca = readcell(fileName); % Read in data from file into a cell array.
t = cell2table(ca) % Convert to a table.
t = 3×4 table
ca1 ca2 ca3 ca4 _________ ___ ___ ___ {'Frank'} 6 2 0 {'Mike' } 0 5 4 {'Ben' } 23 11 2
P = table2array(t(:, 2:end)) % Convert columns 2 onwards into a matrix called P
P = 3×3
6 2 0 0 5 4 23 11 2

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by