How to create separate matrix in workspace for each iteration

2 visualizaciones (últimos 30 días)
Hello everyone , i need help while saving data in loop.
I want to save loop data after each itteration in new workspace with new variable name.Like in first loop i want to save data in variable K_1 and next itteration data want to save in K_2..Is there any way to do..Please help me .Your small effort can solve my problem.
Thank you
  1 comentario
Stephen23
Stephen23 el 6 de Feb. de 2023
Editada: Stephen23 el 6 de Feb. de 2023
"Like in first loop i want to save data in variable K_1 and next itteration data want to save in K_2."
Ugh, do NOT do this!
Numbering variables like that is a sign that you are doing something wrong.
Forcing meta-data (e.g. pseudo-indices) into variable names is a sign that you are doing something wrong.
"Is there any way to do."
Yes, but only if you want to force youself into writing slow, complex, inefficient, obfuscated code:
"Please help me .Your small effort can solve my problem."
Your small effort of using numbered variable names will cause you more problems.
My small effort is to recommend that you use indexing. Indexing is neat, simple, and very efficient (unlike your approach). For example, using a cell array:
N = number of iterations
C = cell(1,N);
for k = 1:N
C{k} = whatever data you want to store
end
There you are: I just solved your problem using simple and efficient code. You're welcome!

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23
Stephen23 el 6 de Feb. de 2023
"I want to save loop data after each itteration in new workspace with new variable name.Like in first loop i want to save data in variable K_1 and next itteration data want to save in K_2."
Do not do that. The name MATLAB comes from "MATrix LABoratory", not from "lets create lots and lots of separate variables in the workspace and make accessing our data more difficult". MATLAB works best with arrays and indexing. You should use arrays and indexing. For example:
N = number of iterations
C = cell(1,N);
for k = 1:N
C{k} = whatever data you want to store
end
Indexing is a MATLAB superpower, if you don't learn how to use it then ... using MATLAB will be very difficult. You can trivially access all of your data using very basic indexing, for example the 2nd data that you saved in the cell array:
C{2}
"Please help me .Your small effort can solve my problem."
Use indexing. Your approach causes problems. Indexing does not.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by