简体   繁体   中英

How to read a matrix from a text in Matlab

I recently ran into this the other day, I'm not that good of a programmer, and the teacher asked us to make a program that reads a square matrix from a txt. and then use the information to solve it. I've been wondering how to do the first part of this program as I already figured it out how to solve the matrix, but I just don't know how to do the scanning of the text. Just so you guys can understand me, this is how the text would look like:

4

1 2 3 8

7 4 1 2

1 2 1 2

3 4 5 6

So as you can see, it has to read the first number and store it in a variable so the program knows the size of the matrix and then read the matrix and store it in an array or so I think.

Any help would be apreciated.

D = importdata('file.txt');
rows = D(1);
cols = (numel(D)-1)/rows;
D = reshape(D(2:end),[cols rows])';

(best MATLAB solution would be to remove the number of rows in the beginning. Then importdata would be sufficient)

suppose file.txt is

1 2 3 8

7 4 1 2

1 2 1 2

3 4 5 6

The command is

load file.txt

and then you get a variable file

the size of file is [4,4] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM