cell array for loop assignment

4 vues (au cours des 30 derniers jours)
Wang Jack
Wang Jack le 12 Mai 2020
Commenté : Dyuman Joshi le 14 Nov 2023
Here is some code
A1 is a 1*4cell array, I want got a 2*4 cell array, but non of those statement can do,
all I got is nesting cell array
anyone any idear?
A2={};
A1={rand(10,2),rand(10,2),rand(10,2),rand(10,2);}
for i=1:4
A2={A2;mat2cell(A{i},[5,5],2)};
A3{i}=mat2cell(A{i},[5,5],2);
A4{:,i}=mat2cell(A{i},[5,5],2);
A5{1,i}=mat2cell(A{i},[5,5],2);
end
A2={};
A={rand(10,2),rand(10,2),rand(10,2),rand(10,2),};
for i=1:4
A2={A2;mat2cell(A{i},[5,5])};
A3{i}=mat2cell(A{i},[5,5]);
A4{:,i}=mat2cell(A{i},[5,5]);
A5{1,i}=mat2cell(A{i},[5,5]);
end
  1 commentaire
Prateek Rai
Prateek Rai le 18 Juin 2020
As per my understanding, you are having a 1*4 cell array from which you want to get 2*4 cell array
You can do this by the following sample code :
Here is a sample code :
A2=cell(2,4);
A={rand(10,2),rand(10,2),rand(10,2),rand(10,2);}
for i=1:4
A2{1,i}=A{i};
A2{2,i}=[5,5]; % fill the data of your interest in new column
end
You can refer to the following documentation for more details .

Connectez-vous pour commenter.

Réponses (1)

Voss
Voss le 14 Nov 2023
A = {rand(10,2),rand(10,2),rand(10,2),rand(10,2)}
A = 1×4 cell array
{10×2 double} {10×2 double} {10×2 double} {10×2 double}
nA = numel(A);
result = cell(2,nA);
for ii = 1:nA
result(:,ii) = {A{ii}(1:end/2,:); A{ii}(end/2+1:end,:)};
end
disp(result);
{5×2 double} {5×2 double} {5×2 double} {5×2 double} {5×2 double} {5×2 double} {5×2 double} {5×2 double}
  1 commentaire
Dyuman Joshi
Dyuman Joshi le 14 Nov 2023
An approach without loops -
A = {rand(10,2),rand(10,2),rand(10,2),rand(10,2)}
A = 1×4 cell array
{10×2 double} {10×2 double} {10×2 double} {10×2 double}
B = horzcat(A{:})
B = 10×8
0.1565 0.9521 0.7572 0.6869 0.7378 0.4813 0.8155 0.1594 0.2282 0.4625 0.9511 0.7689 0.4404 0.3185 0.4336 0.3613 0.6424 0.8441 0.7075 0.3435 0.3700 0.1041 0.1690 0.1084 0.6138 0.8827 0.8309 0.5593 0.5412 0.0326 0.1012 0.4879 0.1479 0.5416 0.4597 0.4603 0.7875 0.3722 0.5623 0.9909 0.4484 0.7419 0.6389 0.5388 0.0598 0.4542 0.5955 0.8836 0.2918 0.5863 0.5799 0.5679 0.5118 0.8944 0.6441 0.8400 0.0530 0.5036 0.4431 0.2935 0.1843 0.4312 0.3931 0.4805 0.3789 0.1006 0.3056 0.5012 0.3816 0.1229 0.2707 0.2895 0.2958 0.3525 0.5879 0.4889 0.8968 0.5852 0.2676 0.3825
C = mat2cell(B, [5 5], [2 2 2 2])
C = 2×4 cell array
{5×2 double} {5×2 double} {5×2 double} {5×2 double} {5×2 double} {5×2 double} {5×2 double} {5×2 double}
%For verification
C{1}
ans = 5×2
0.1565 0.9521 0.2282 0.4625 0.6424 0.8441 0.6138 0.8827 0.1479 0.5416

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by