How to know the size of a matrix inside a for loop
2 views (last 30 days)
Show older comments
Hello,
I would like to know the size of a group of matrices in a for loop.
I tried this
size(strcat('MediaOfDay_',sprintf('%02d',10)),2)
But instead of obtaining the size of the matrix I'm getting the size o the string.
What am I doing wrong.
Thank you in advance
1 Comment
Stephen23
on 2 Nov 2023
Edited: Stephen23
on 2 Nov 2023
"What am I doing wrong."
"I would like to know the size of a group of matrices in a for loop."
You forgot to tell us the most important information: how did you get all of those matrices into the workspace? Did you write all of their names by hand, or LOAD them from MAT file/s, or magically create them using some code? That is the location where you need to fix that bad data design... the result will make your task much much easier.
This is exactly the same advice in some of your earlier questions:
Answers (1)
Arun
on 3 Jan 2024
Hi Ricardo,
I understand that you wish to know the size of different matrices within a loop but get the size of the matrix’s name as a string.
The “eval” function can be used to evaluate the string and thus can be used to find the size of the required matrix.
Here is a sample code snippet that could be useful:
MediaOfDay_01 = zeros(2,3);
MediaOfDay_02 = zeros(5,3);
MediaOfDay_03 = zeros(4,3);
MediaOfDay_11 = zeros(4,11);
for i = [1:3 11]
size(eval(strcat('MediaOfDay_',sprintf('%02d',i)))) % size of matrix
size(eval(strcat('MediaOfDay_',sprintf('%02d',i))),2) % number of column
end
For additional information regarding the “eval” function, please refer the following MATLAB documentation:
However, the “eval” function is not always the best solution as it can unexpectedly create or assign to a variable already to a variable in the current workspace, overwriting existing data.
The preferred way to store data is to create a cell array or structure array.
Here is sample code that could be useful:
MediaOfDay_01 = zeros(2,3);
MediaOfDay_02 = zeros(5,3);
MediaOfDay_03 = zeros(4,3);
MediaOfDay_11 = zeros(4,11);
A = cell(4,1);
A{1} = MediaOfDay_01;
A{2} = MediaOfDay_02;
A{3} = MediaOfDay_03;
A{4} = MediaOfDay_11;
for i =1:4
size(A{i},2)
end
For more information related to alternatives to the “eval” function, please refer the following MATLAB documentation:
I hope this helps.
0 Comments
See Also
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!