Split cell arrays into seperate matrix; Indexing problem with cell array
8 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Siegfried Suthau
le 27 Août 2020
Modifié(e) : Stephen23
le 27 Août 2020
Hello guys, thank you very much in advance. I woul like to split up a cell array (NxM) with (1xR) double elements in each cell into m matrix or tables with (NxM).
For your further information about my situation: I have different simulation settings (NxM) and i have different result outputs which are the data in each cell (1xR).
My goal is to get a matrix or table for each result. That means I want R matrix with (NxM) Data of the fitting result
Maybe you could help me with a neat solution
a={[1,2],[1,2],[1,2];[1,2],[1,2],[1,2];[1,2],[1,2],[1,2]} %easy number exmaple
%%%%%%%%%%
Result1=[1,1,1;1,1,1;1,1,1]%Result matrix 1; Result1 through indexing of a
Result2=[2,2,2;2,2,2;2,2,2]%Result matrix 2;Result2 through indexing of a
This is probably trivial but I am not able to make it work without using a for-loop. And everytime I use a for-loop i get stuck with the variable naming of the result matrix.
Thank you very much!
1 commentaire
Stephen23
le 27 Août 2020
"And everytime I use a for-loop i get stuck with the variable naming of the result matrix."
Why do you want to force yourself into writing slow, complex, obfuscated, buggy code that is hard to debug?
Indexing is much neater, simpler, more efficient, less buggy, and easier to debug.
Réponse acceptée
Stephen23
le 27 Août 2020
Modifié(e) : Stephen23
le 27 Août 2020
"Maybe you could help me with a neat solution"
The neat solution is to use MATLAB's arrays effectively. For example, something like this:
>> a = {[1,2],[1,2],[1,2];[1,2],[1,2],[1,2];[1,2],[1,2],[1,2]};
>> s = size(a);
>> m = reshape(vertcat(a{:}),s(1),s(2),[]);
>> m(:,:,1) % index 1st page
ans =
1 1 1
1 1 1
1 1 1
>> m(:,:,2) % index 2nd page
ans =
2 2 2
2 2 2
2 2 2
Using different values makes the example clearer:
>> a = {[1,2],[3,4],[5,6];[7,8],[9,10],[11,12];[13,14],[15,16],[17,18]};
>> s = size(a);
>> m = reshape(vertcat(a{:}),s(1),s(2),[]);
>> m(:,:,1) % index 1st page
ans =
1 3 5
7 9 11
13 15 17
>> m(:,:,2) % index 2nd page
ans =
2 4 6
8 10 12
14 16 18
>> c = num2cell(m,1:2); % optional: a cell array may be convenient in some situations.
>> c{1} % index 1st cell
ans =
1 3 5
7 9 11
13 15 17
>> c{2} % index 2nd cell
ans =
2 4 6
8 10 12
14 16 18
2 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!