Info

This question is closed. Reopen it to edit or answer.

Can I use dlmread() twice within a function?

2 views (last 30 days)
xiufen xu
xiufen xu on 30 Sep 2017
Closed: MATLAB Answer Bot on 20 Aug 2021
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
xiufen xu
xiufen xu on 2 Oct 2017
You are right. This is way, I can get Matrix1 and Matrix2. But when I run
>> ReadData(training_filename, test_filename)
I only get Matrix1. Could you explain this? Thanks!
Walter Roberson
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
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.
  2 Comments
xiufen xu
xiufen xu on 2 Oct 2017
Hi Donald! Thanks for your help. But I only got Matrix1 and failed at getting Matrix2. Do you know why?
OCDER
OCDER on 2 Oct 2017
Edited: OCDER on 2 Oct 2017
How did you run the function? Should have worked. If not, can you upload the txt file you are trying to read?
>> [M1, M2] = ReadData('data1.txt')
M1 =
1 2 3 4
6 7 8 9
1 2 3 4
6 7 8 9
M2 =
5 0 5 0

This question is closed.

Community Treasure Hunt

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

Start Hunting!