How to read file .txt?

조회 수: 8 (최근 30일)
Mira le
Mira le 2019년 12월 9일
댓글: Amir Shahang 2021년 12월 4일
I have file .txt contains
1 2
2 3
I want to read the file and put each value 12 , 23 in a cell array
How can I do that
Please help me.
Thanks
  댓글 수: 6
Adam Danz
Adam Danz 2019년 12월 9일
@Mira le , please take a moment to think about the questions that dpb and Guillaume have asked. They are important.
Do you want this
{12, 23}
or this
{[1,2],[2,3]}
or something else?
If the answer is something else, show us exactly what you're looking for.
Mira le
Mira le 2019년 12월 9일
I mean {[1,2],[2,3]}
If i want to put then in s for example like that
s={[1,2],[2,3]}
s =
1×2 cell array
[1×2 double] [1×2 double]
>> s{1}
ans =
1 2
>> s{2}
ans =
2 3

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

채택된 답변

Adam Danz
Adam Danz 2019년 12월 9일
편집: Adam Danz 2019년 12월 9일
Assuming your text file is named myTextFile.txt and contains only that matrix,
A = readmatrix('myTextFile.txt'); % for Matlab >= 2019a
%A = dlmread('myTextFile.txt'); % for matlab < r2019a
B= mat2cell(A,[1,1],2).'; % If you want to split the matrix by rows
B= mat2cell(A.',[1,1],2).'; % If you want to split the matrix by columns
In your example it's unclear whether your splitting the matrix by rows or by columns since both result in the same output. Use the 2nd line above to split by rows and the 3rd line to split by columns. Both produce a 1x2 cell containing two 1x2 vectors.
[update]
This version below is more generalizeable in case the size of your matrix changes.
B = mat2cell(A,ones(size(A,1),1),size(A,2)).'; %by row....
B = mat2cell(A.',ones(size(A,2),1),size(A,1)).'; %by column...
  댓글 수: 6
Mira le
Mira le 2019년 12월 10일
Thanks
Amir Shahang
Amir Shahang 2021년 12월 4일

That works for me too, thanks

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

태그

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by