create number of arrays dynamicly
Mostrar comentarios más antiguos
i have a matrix of [m,n], i want to create m arrays and store those m rows into those m arrays. any way of doing that? example: a=[1 2 3 4;5 6 7 8;9 10 11 12] this matrix has 3 rows so i want to create three arrays(A1,A2,A3) and store A1=[1 2 3 4] A2=[5 6 7 8] A3=[9 10 11 12] thanks in advance
Respuesta aceptada
Más respuestas (2)
Guillaume
el 27 de En. de 2016
"but i want these arrays to be visible in my workspace"
Why would you want that? If they are different variables, you can't loop over them, you can't process them generically, you can't extend your code to have more arrays, etc.
It's simply bad practice, has lots of downside, and no obvious advantage.
Compare:
%split the matrix into row vectors, REGARDLESS OF THE NUMBER OF ROWS
a_by_row = num2cell(a, 2);
%send the individual arrays to the same function
%REGARDLESS OF THE NUMBER OF ROWS
for row = 1:numel(a_by_rows)
dosomething(a_by_row{row});
end
%concatenate the arrays, REGARDLESS OF THE NUMBER OF ROWS
catarray = cat(1, a_by_rows{:});
%etc.
With:
%split into individual variables
for row = 1:size(a, 1)
eval(sprintf('A%1$d = a(%1$d, :)', row)); %how do you debug that ?
end
%call function on each variable, welcome to copy-paste (or more eval?)
dosomething(A1);
dosomething(A2);
dosomething(A3);
%now if you add more rows, you need to copy-paste more
%concatenate the arrays:
cat(1, A1, A2, A3); %again more copy-paste if more rows.
Do NOT create arrays dynamically. Creating arrays dynamically is a really bad way to program. Read this to know why:
Better Solution
Instead you could put the arrays into a cell array:
>> a=[1 2 3 4;5 6 7 8;9 10 11 12]
a =
1 2 3 4
5 6 7 8
9 10 11 12
>> X = num2cell(a,2);
>> X{:}
ans =
1 2 3 4
ans =
5 6 7 8
ans =
9 10 11 12
Best Solution
However the best solution would be to leave the data exactly as it is in the numeric array. Just loop over the rows of the data matrix. There is no point in splitting this data up into smaller arrays.
5 comentarios
Himanshu Tomar
el 27 de En. de 2016
Walter Roberson
el 27 de En. de 2016
Did you read the links?
Himanshu Tomar
el 27 de En. de 2016
Categorías
Más información sobre Logical en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!