Loop to extract rows from matrix
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi, I need to extract each rows of a matrix creating different variables. How a can do it? Thanks in advance!
0 commentaires
Réponse acceptée
Jan
le 29 Août 2017
Don't do this. The topic is discussed daily in this forum, see e.g. https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval.
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 commentaires
Adam
le 30 Août 2017
Why can't you just create the text files from the one initial array, taking a row at a time?
Jan
le 30 Août 2017
Modifié(e) : Jan
le 30 Août 2017
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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Data Types dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!