Loading a text file with strings and numbers

I am trying to load in a txt file that has strings and numbers. The attached text file is organized with 1 column and 5 rows containing “a 2 t 1.5 n”. The only number is “1.5” with the rest being strings.
I need the code to store each item as a separate variable. For example variable 1 = a, variable 2 = 2, variable 3 = t ect.
Any help would be greatly appreciated.

1 件のコメント

Adam Danz
Adam Danz 2020 年 1 月 13 日
"The only number is “1.5”..."
I see a 2 in there, too.

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

回答 (1 件)

Adam Danz
Adam Danz 2020 年 1 月 13 日
編集済み: Adam Danz 2020 年 1 月 13 日

0 投票

"The only number is “1.5”..."
I see a 2 in there, too.
"I need the code to store each item as a separate variable."
That would require dynamic variable naming which is a bad practice that results in additional problems. See https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
A better solution it to store the values in a cell array that you can reference by indexing.
The first line reads in the text file as a cell array of character vectors.
The second line converts any character vectors that are numeric to numeric values.
c = strsplit(fileread('Test.txt')).';
c(~isnan(cellfun(@str2double,c))) = num2cell(str2double(c(~isnan(cellfun(@str2double,c)))));
Now you can access the n-th value by indexing
c{n}

4 件のコメント

Adam Bosco
Adam Bosco 2020 年 1 月 13 日
For the sake of the code, the 2 is used as a string. Sorry for the confusion.
Thank you for the help!
Adam Danz
Adam Danz 2020 年 1 月 13 日
Hmmm, how will Matlab know which elements to convert to numeric? Or, are you keeping all elements as strings or char-arrays? If that's what you're doing, you'll only need the first line of my answer.
Does this solve the problem for you?
Adam Bosco
Adam Bosco 2020 年 1 月 13 日
Yep this solved my problem. Thanks!
Adam Danz
Adam Danz 2020 年 1 月 13 日
編集済み: Adam Danz 2020 年 2 月 25 日
Glad I could help.

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

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

タグ

質問済み:

2020 年 1 月 13 日

編集済み:

2020 年 2 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by