Effacer les filtres
Effacer les filtres

I would like to save each Thex array created in each loop as its own array. How can i create a variable that has its name adjusted with each loop and saves each loop result?

30 vues (au cours des 30 derniers jours)
Hayat
Hayat le 26 Juin 2024 à 4:13
Modifié(e) : Stephen23 le 26 Juin 2024 à 8:14
  1 commentaire
Stephen23
Stephen23 le 26 Juin 2024 à 4:49
Modifié(e) : Stephen23 le 26 Juin 2024 à 8:14
"I would like to save each Thex array created in each loop as its own array"
Every cell of a cell array contains "its own array", so your code already does that.
"How can i create a variable that has its name adjusted with each loop and saves each loop result?"
Ugh, do NOT do that. Why do you particularly need to force yourself into writing slow, complex, inefficient, obfuscated, buggy code that is hard to debug and much harder to maintain?
Instead of asking us about your anti-pattern approach, tell us what you are actually trying to achieve:

Connectez-vous pour commenter.

Réponses (2)

Steven Lord
Steven Lord le 26 Juin 2024 à 4:25
Can you dynamically create variables with numbered names like T1, T2, T3, etc.? Yes.
Should you do this? The general consensus is no. That Discussions post explains why this is generally discouraged and offers several alternative approaches. A cell array, as you've shown here, is one of those alternate approaches. If they arrays you're trying to store are all the same size and type, using a multidimensional array is another possibility.

Ashutosh Thakur
Ashutosh Thakur le 26 Juin 2024 à 4:31
Hi Hayat,
Cell arrays can be leveraged in your use case to store the result of the Thex variable created inside the loop. The following steps can be followed:
  • First, create a cell array with a preallocated size. In your case, it should be the number of iterations of the loop. For more information, you can refer to the following link: https://www.mathworks.com/help/matlab/cell-arrays.html.
  • For each iteration, store the value of the Thex variable in the new cell array created.
  • You can access the elements of your array by looping or using indexing.
Following sample code can be referred to implement the above steps:
n = 5; % Number of loops
ThexArray = cell(1, n); % Preallocate a cell array
for i = 1:n
% Some code ....
Thex = delaunay(x,y,z);
ThexArray{i} = Thex; % storing the Thex variable in the ThexArray
end
% Accessing the saved arrays
for i = 1:n
disp(ThexArray{i});
end
Please note that use curly brackets "{}" to access the elements of the cell array.
I hope this helps!

Catégories

En savoir plus sur Loops and Conditional Statements 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!

Translated by