Loop to extract rows from matrix

Hi, I need to extract each rows of a matrix creating different variables. How a can do it? Thanks in advance!

 采纳的回答

Jan
Jan 2017-8-29

2 个投票

The dynamic creation of a bunch of vectors causes troubles. It is even worse, if you want to use these vectors later on. To access a column of a matrix, simply use an index: A(:, i) is the i.th column. This is fast, clean and simple.
Please explain, why you assume that creating a set of variables is useful in your case. I'm sure, that the forum can give you better options to solve the actual problem.

3 个评论

Many thanks for the link. I have a matrix with 228 rows and a need to create a 228 matrix with one row in order to create a txt file from each of them.
As example: I have this matrix
A=[1,2.30,43.66,21.42,6.63;1,2.30,24.22,34.37,1.20;1,2.30,33.72,28.54,12.38;];
and I need to create those matrices:
1=[1,2.30,43.66,21.42,6.63];
2=[6.63;1,2.30,24.22,34.37,1.20];
3=[1,2.30,33.72,28.54,12.38];
and finally create from each of those matrices a .txt files using the following code but implemented for a loop:
% the data
fnam='test.txt'; %
hdr={'a ','b','c'}; % First header%
hdr2={'(m)','(%)','(%)'}; % Second Header%
m = data %rows from matrix
% the engine
fmt = repmat('%s\t ', 1, length(hdr));
fmt(end:end+1) = '\n';
fid = fopen(fnam, 'w');
fprintf(fid, fmt, hdr{:});
fprintf(fid, fmt, hdr2{:});
fclose(fid);
dlmwrite(fnam,m,'-append','delimiter','\t');
% the result
type(fnam)
The final result that I want obtait could be a three different .txt files: 1.txt 2.txt 3.txt Thanks in advance!
Why can't you just create the text files from the one initial array, taking a row at a time?
Again: No, you do not need to create the vectors explicitly. Trying to do so is a shot in your knee. A(iRow, :) is perfect already.
Do you want to create 228 files? Then:
hdr = {'a ','b','c'}; % First header%
hdr2 = {'(m)','(%)','(%)'}; % Second Header%
fmt = repmat('%s\t ', 1, length(hdr));
fmt(end:end+1) = '\n';
for iRow = 1:size(A, 1);
fnam = sprintf('test%03d.txt', iRow);
fid = fopen(fnam, 'w');
fprintf(fid, fmt, hdr{:});
fprintf(fid, fmt, hdr2{:});
fclose(fid);
dlmwrite(fnam, A(iRow, :), '-append', 'delimiter', '\t');
end
This can be done directly also without dlmwrite:
fmtData = [repmat('%g\t', 1, size(A, 2) - 1), '%g\n'];
...
fprintf(fid, fmt, hdr2{:});
fprintf(fid, fmtData, A(iRow, :));
fclose(fid);
end

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Data Types 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by