How to know the size of a matrix inside a for loop

2 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2023-11-2
编辑:Stephen23 2023-11-2
"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:

请先登录,再进行评论。

回答(1 个)

Arun
Arun 2024-1-3
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
ans = 1×2
2 3
ans = 3
ans = 1×2
5 3
ans = 3
ans = 1×2
4 3
ans = 3
ans = 1×2
4 11
ans = 11
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
ans = 3
ans = 3
ans = 3
ans = 11
For more information related to alternatives to the “eval” function, please refer the following MATLAB documentation:
I hope this helps.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by