Info
This question is closed. Reopen it to edit or answer.
Can I use dlmread() twice within a function?
2 views (last 30 days)
Show older comments
I am pretty new to Matlab. I want to read data from a text file into several matrices. For example, the text file contains
1,2,3,4,5
6,7,8,9,0
1,2,3,4,5
6,7,8,9,0
I want to break these data into two matrices. The first matrix(4*4) is
1 2 3 4
6 7 8 9
1 2 3 4
6 7 8 9
The second matrix(4*1), which is also a vector is
5 0 5 0
My code is
function [Matrix1, Matrix2] = ReadData(training_filename, test_filename)
Matrix1 = dlmread(training_filename, ',', [0 0 3 3]);
Matrix2 = dlmread(training_filename, ',', [0 4 3 4]);
end
Running this code I only get Matrix1 but fail at getting Matrix2. However, if I change the output_args order, like:
function [Matrix2, Matrix1] = ReadData(training_filename, test_filename)
Matrix1 = dlmread(training_filename, ',', [0 0 3 3]);
Matrix2 = dlmread(training_filename, ',', [0 4 3 4]);
end
I get Matrix2 but failed at getting Matrix1. Is there anyone know what the problem is? Thanks.
3 Comments
Walter Roberson
on 2 Oct 2017
It is part of MATLAB's design that when a function has multiple outputs and you do not assign the outputs to anything, that the result of executing the function is just the first output. Then, by default, that first output would be displayed.
Answers (1)
OCDER
on 1 Oct 2017
Edited: OCDER
on 1 Oct 2017
One way to do this is to load all data, and then split into Matrix1 and Matrix2. I assume you want Matrix1 to have all columns except last one. Matrix2 to have just the last column.
function [Matrix1, Matrix2] = ReadData(training_filename, test_filename)
Matrix = dlmread(training_filename, ',');
Matrix1 = Matrix(:, 1:end-1); %Takes 1st to last-1 column
Matrix2 = Matrix(:, end)'; %Takes last column only, and transpose to get 1x4 matrix
%Note: you don't use test_filename here. Consider using it or remove from the input.
This question is closed.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!