Conversion of cell array into individual object

8 visualizaciones (últimos 30 días)
Rajan Patel
Rajan Patel el 11 de Sept. de 2020
Comentada: André Galera el 27 de Oct. de 2020
I have 324*231 cell array M.
  1. M(2:end,1) includes names of countries
  2. M(2:end,2) includes names of respective states
  3. M(2:end,3:end) includes some data ( each in {1*2 double} ).
I want to make individual object of each country which contain their states which contain their respective data. So, sort of three level hierarchy.How should I initiate?
Thanks.

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 11 de Sept. de 2020
Editada: Ameer Hamza el 11 de Sept. de 2020
What about using a struct to save data hierarchically. For example
M = [{"C1"; "C1"; "C2"; "C3"; "C3"; "C3"}, ...
{"S1"; "S2"; "S1"; "S1"; "S2"; "S3"}, ...
num2cell(rand(6,3))];
countries = unique([M{:,1}]);
M1 = splitapply(@(x) {x}, M(:,2:end), findgroups([M{:,1}]).');
temp = [num2cell(countries); cell(size(countries))];
S = struct(temp{:});
for i=1:numel(countries)
country_data = M1{i};
for j=1:size(country_data, 1)
S.(countries(i)).(country_data{j,1}) = country_data(j, 2:end);
end
end
C1, C2, and C3 are country names, and S1, S2, and S3 are names of states within a specific country.
Run it like this
>> S.C1.S1 % displays the data for country=C1 and state=S1
ans =
1×3 cell array
{[5.2238e-04]} {[0.8013]} {[0.7386]}
  5 comentarios
Ameer Hamza
Ameer Hamza el 14 de Sept. de 2020
In this case, myObj < handle will have no difference in the output, but it is usually slower. The difference is that handle objects behave somewhat similarly to pointers in C or C++.
André Galera
André Galera el 27 de Oct. de 2020
Hello, there! This code is just what I needed as well! But I am getting an error. Could you help me? When I run your example, it works fine. But if I run with my cell array (also 324*321) I get the error showed in the image below. Thanks!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Construct and Work with Object Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by