MATLAB: How to transform a matrix from a text file to numeric matrix to perform calculations with.

matrixstring

Hello.
I have a matrix in a file(which i have attached) and after using fopen i have used fgetl to read the matrix but it reads into a string and i need to perform calculations with every single onde of the elements in the matrix and it has to have the elements in the exact order as they where in the text file. In the end what i basically want is a matrix where afterwards i can use it to acess it's elements and do calculations with them.
I am only allowed to use functions that are in the book "MATLAB A Pratical Introduction to Programming and Problem Solving" so i am having some troubles with this.
while feof(f) == 0
matrix = fgetl(f);
end
Thanks for the help.

Best Answer

As per Stephen's comment, I'd recommend using dlmread (or similar csvread) or at a push textscan (which makes the code more complicated that it needs to be). If, for some reason, that is not allowed and you really want to do it the complicated and slow way, then you can indeed use fgetl.
The first problem with your code
while feof(f) == 0
matrix = fgetl(f);
end
is that each time you call fgetl you overwrite the matrix variable (whose name is really misleading, it's just one line of text) with the content of the line.
You can either store each line as row of a char matrix (fragile, will error if a line has more characters than the others):
lines = '';
while feof(f) == 0
lines(end+1, :) = fgetl(f);
end
Or as a cell array of char vectors:
lines = {};
while feof(f) == 0
lines{end+1} = fgetl(f);
end
Or convert as you read the line, and then store in a matrix or cell array of numbers:
matrix = {}; %or matrix = [];
while feof(f) == 0
line = fgetl(f);
matrix{end+1, 1} = str2double(strsplit(line));
%or matrix(end+1, :) = str2double(strsplit(line)); %but will error if not all lines have the same number of elements
end
%only for cell arrays:
try
matrix = cell2mat(matrix);
catch
error('some rows have more numbers than others');
end
Note that I use str2double instead of str2num. str2num isn't safe. It will happily format your hard drive if you pass it 'rmdir('c:\', 's'). Since you have no idea what is in the text file you're parsing, you should assume it can be hostile.