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

3 Ansichten (letzte 30 Tage)
Ricardo Duarte
Ricardo Duarte am 2 Nov. 2023
Beantwortet: Arun am 3 Jan. 2024
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 Kommentar
Stephen23
Stephen23 am 2 Nov. 2023
Bearbeitet: Stephen23 am 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:

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Arun
Arun am 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
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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by