Adding row to matrix in a loop

I have a folder with many files (file_1, file_2 ... file_n), each of them contains variables (A, B, C ...). I need to work with several files (number of files varies) that I specifically choose from the folder (eg. file_1, file_7, file_22, ... file_m) - load the file, calculate some stuff and save the result as a new row to a matrix and then do this for another file etc.
I ´ve been thinking of using for loop to load and calculate, but I can´t figure out how to add a new row to a matrix after every loop. I tried "cat", but it didn´t work the way I need. Or is there a better solution?
And furthemore I need to plot the results in one graph the way I can specify the plot details for a group of files (eg. plot the first 10 results in red, the next ones in green, etc.). I can´t do it manually, because there are dozens of files.
Thanks in advance!

 采纳的回答

Adam Danz
Adam Danz 2020-4-14
编辑:Adam Danz 2020-4-18
If and only if the matrices have the same number of columns, you can concatenate two matrices vertically using,
M = [m1; m2]; % where m1 and m2 are matrices with the same number of columns.
To add a new row,
M(end+1,:) = NaN; % or 0, or any other scalar value.
Another solution would be to save the matrices within a cell array and concatenate them later, after the loop; again, equal column numbers are required.
C = cell(n,1);
for i = 1:n
C{i} = mat; % mat is a matrix
end
M = vertcat(C{:});
Once the matrix is complete, the plot() function will plot one line object per column
plot(M, '-')

3 个评论

Thank you for your answer, Adam.
Yes, both matrices have the same number of columns. I use the second solution you mentioned, it works, but I had to use
C{i} = mat
instead of
C{1} = mat
to get a new row after every loop. And also I could omit
C = cell(n,1)
So my code is now
for i = 1:n;
% calculating stuff
mat = [X Y Z];
C{i} = mat;
end
M = vertcat(C{:});
Thanks for pointing out that typo, Peter. I fixed it in the answer so it doesn't cause future confusion.
Your updated version looks good except for two small stylistic corrections you can make:
  1. Indent the lines within the for-loop (ctrl + a to select all; ctrl + i for smart indentation),
  2. Suppress the output from the first line of the for-loop by adding a semicolon to the end of the line (I realize it's probably just a demo-line).
Corrections done. Thanks for the great tip, I didn´t know about the ctr+i shortcut.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by