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 次查看(过去 30 天)
显示 更早的评论
1 个评论
Stephen23
2024-6-26
编辑:Stephen23
2024-6-26
"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:
回答(2 个)
Steven Lord
2024-6-26
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.
0 个评论
Ashutosh Thakur
2024-6-26
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!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!