generate out put names and output number dynamically

1 visualizzazione (ultimi 30 giorni)
Im have hard code K but I want to change it so K will be generated i have done that part
the problem is G1 to G5 veriables should be change from G1 to GK
how can I do this
K=5 % specify and hard code K number of clastors
X;
[IDX, centr] = kmeans( X , K , 'distance' , 'sqEuclidean');% K number of clustors
% separate the data into five groups
G1 = Y2(IDX == 1 , : );
G2 = Y2(IDX == 2 , : );
G3 = Y2(IDX == 3 , : );
G4 = Y2(IDX == 4 , : );
G5 = Y2(IDX == 5 , : );
I try this simply didt work
[IDX, centr] = kmeans( X , K , 'distance' , 'sqEuclidean');% K number of clustors
for g=1:K
G(g) = Y2(IDX == g , : )
end
  3 Commenti
Stephen23
Stephen23 il 9 Feb 2023
Modificato: Stephen23 il 9 Feb 2023
"the problem is G1 to G5 veriables should be change from G1 to GK"
The problem is that you are forcing meta-data (i.e. pseudo-indices) into variable names.
"how can I do this "
Rather than attempting to force pseudo-indices into variable names, you should be using actual indices.
How to use arrays, loops, and indexing is explained in the introductory tutorials:
The name "MATLAB" comes from "MATrix LABoratory", not from "lets split up the data into lots and lots of separate variables and make working with the data slow and complex". MATLAB is designed to work with arrays. You should use arrays.
Dyuman Joshi
Dyuman Joshi il 9 Feb 2023
@Stephen23 I think OP is trying to use arrays but failed in the attempt as they have mentioned.

Accedi per commentare.

Risposta accettata

Stephen23
Stephen23 il 9 Feb 2023
Modificato: Stephen23 il 9 Feb 2023
Because you did not upload any data I will use an inbuilt dataset:
S = load('fisheriris.mat');
X = S.meas(:,3:4);
Now lets group that data:
[idx,C] = kmeans(X,2) % keep it simple
idx = 150×1
2 2 2 2 2 2 2 2 2 2
C = 2×2
4.9253 1.6818 1.4922 0.2627
F = @(n) X(idx==n,:);
C = arrayfun(F,1:max(idx),'uni',0)
C = 1×2 cell array
{99×2 double} {51×2 double}
Checking:
C{:}
ans = 99×2
4.7000 1.4000 4.5000 1.5000 4.9000 1.5000 4.0000 1.3000 4.6000 1.5000 4.5000 1.3000 4.7000 1.6000 3.3000 1.0000 4.6000 1.3000 3.9000 1.4000
ans = 51×2
1.4000 0.2000 1.4000 0.2000 1.3000 0.2000 1.5000 0.2000 1.4000 0.2000 1.7000 0.4000 1.4000 0.3000 1.5000 0.2000 1.4000 0.2000 1.5000 0.1000
Note that splitting up data is often not a good approach, it is the kind of thing that users do because they think it is required for processing of their data. In fact, MATLAB has tools that support working on entire datsets without splitting them up into separate arrays:

Più risposte (0)

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by