How to open a file .txt in MATLAB

조회 수: 24 (최근 30일)
vinicius lanziotti
vinicius lanziotti 2017년 12월 8일
댓글: Michal Dobai 2017년 12월 8일
a = input('\nEnter with a matrix .txt: ');
archive = fopen('a');
b = fscanf(archive,'%f',[3 3]);
fclose(archive);
When I run this code it gives error.

채택된 답변

Michal Dobai
Michal Dobai 2017년 12월 8일
OK. Let's say that you already have file named 'abc.txt' in your workspace and it looks like this:
1 2 3
4 5 6
7 8 9
Then your code will work as expected, if:
  • First about input() function:
a = input('\nEnter with a matrix .txt: ');
Documentation : x = input(prompt) displays the text in prompt and waits for the user to input a value and press the Return key. The user can enter expressions, like pi/4 or rand(3), and can use variables in the workspace.
If you type in the console abc.txt without apostrophes you will get this error:
Undefined variable "abc" or class "abc.txt".
That's because MATLAB will conciser input as expresion and try to evaluate it, so abc is considered as variable, but no such variable exist in your workspace. Now, you can do 2 things:
  1. Type name of the file with apostrophes e.g. 'abc.txt', or
  2. add argument 's' into input() function call
a = input('\nEnter with a matrix .txt: ', 's')
MATLAB will then consider user input as text and will not try to evaluate the input as an expression. Now you can type the file name without apostrophes.
  • Next problem in your code is second line. Function fopen() takes one argument - name of file. You already have name of file you want to open in variable a, but in your code you're trying to open file named 'a'. That's because in MATLAB, everything in apostrophes is text (more specific - char array). If you want to use value of your variable a as input for fopen(), you have to type it without apostrophes, like this:
archive = fopen(a);
Final code will then look like this:
a = input('\nEnter with a matrix .txt: ', 's');
archive = fopen(a);
b = fscanf(archive,'%f',[3 3])
fclose(archive);
  댓글 수: 2
vinicius lanziotti
vinicius lanziotti 2017년 12월 8일
Very good! Thanks very much.
Michal Dobai
Michal Dobai 2017년 12월 8일
You're welcome.
If something is still not clear to you, you can ask here, I'll try to explain it to you in further detail. If you tried this solution, and it works as expected, you could consider to accept this answer :)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by