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?

2 views (last 30 days)
  1 Comment
Stephen23
Stephen23 on 26 Jun 2024
Edited: Stephen23 on 26 Jun 2024
"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:

Sign in to comment.

Answers (2)

Steven Lord
Steven Lord on 26 Jun 2024
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 on 26 Jun 2024
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!

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!