Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Can I use dlmread() twice within a function?

2 ビュー (過去 30 日間)
xiufen xu
xiufen xu 2017 年 9 月 30 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
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 件のコメント
xiufen xu
xiufen xu 2017 年 10 月 2 日
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 2017 年 10 月 2 日
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.

回答 (1 件)

OCDER
OCDER 2017 年 10 月 1 日
編集済み: OCDER 2017 年 10 月 1 日
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 件のコメント
xiufen xu
xiufen xu 2017 年 10 月 2 日
Hi Donald! Thanks for your help. But I only got Matrix1 and failed at getting Matrix2. Do you know why?
OCDER
OCDER 2017 年 10 月 2 日
編集済み: OCDER 2017 年 10 月 2 日
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

この質問は閉じられています。

Community Treasure Hunt

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

Start Hunting!

Translated by