Converting 1x1 struct with multiple fields to numeric matrix
20 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Mark Archibald
el 27 de Nov. de 2024
Respondida: Matt J
el 27 de Nov. de 2024
I have a 1x1 structure with multiple fields containing either a single number or a cell array. The cell array is integers seperated by commas. i want to convert this into a matrix in which missing values are filled in with zeros.
Example: Create a structure:
tieup.x1 = '2,3,6';
tieup.x2 = 3;
tieup.x3 = 4;
tieup.x4 = '1,4,5';
tieup.x5 = '1,2,3,6';
This creates a struct with fields:
x1: '2,3,6'
x2: 3
x3: 4
x4: '1,4,5'
x5: '1,2,3,6'
I want to convert to a matrix that looks like
desiredmatrix =
0 2 3 0 0 6
0 0 3 0 0 0
0 0 0 4 0 0
1 0 0 4 5 0
1 2 3 0 0 6
Please help me do this.
1 comentario
Matt J
el 27 de Nov. de 2024
containing either a single number or a cell array.
I don't see numbers and cell arrays. I see numbers and char vectors
Respuesta aceptada
Epsilon
el 27 de Nov. de 2024
Editada: Epsilon
el 27 de Nov. de 2024
Hi Mark,
An approach to convert the struct to the desired matrix can be to extract the elements and then use pre allocation to make the matrix of the size needed. The data can then be filled inside the matrix at the desired row location with the same value.
tieup.x1 = '2,3,6';
tieup.x2 = 3;
tieup.x3 = 4;
tieup.x4 = '1,4,5';
tieup.x5 = '1,2,3,6';
% Extract field names and initialize
fieldNames = fieldnames(tieup);
numFields = numel(fieldNames);
% Determine the maximum column index needed
max_col = 0;
for i = 1:numFields
numbers = str2num(num2str(tieup.(fieldNames{i})));
max_col = max(max_col, max(numbers));
end
% Initialize and fill the matrix
desiredmatrix = zeros(numFields, max_col);
for i = 1:numFields
numbers = str2num(num2str(tieup.(fieldNames{i})));
desiredmatrix(i, numbers) = numbers;
end
% Display the result
disp(desiredmatrix);
Basically the loop iterates over each field in the structure, converts the field's value (whether it's a string or a number) into a numeric array, and then fills the corresponding row in the matrix with these numbers. Any positions in the row not specified by numbers remain zero, effectively filling the matrix with numbers from the structure while leaving gaps as zeros.
Glad to help!
0 comentarios
Más respuestas (1)
Matt J
el 27 de Nov. de 2024
tieup.x1 = '2,3,6';
tieup.x2 = 3;
tieup.x3 = 4;
tieup.x4 = '1,4,5';
tieup.x5 = '1,2,3,6';
f=string(fieldnames(tieup))';
N=numel(f);
[I,J]=deal(cell(1,N));
for k=1:numel(f)
J{k}=tieup.(f(k));
if ischar(J{k}), J{k}=str2num(J{k}); end
I{k}=repelem(k,1,numel(J{k}));
end
result = accumarray([[I{:}]' , [J{:}]'], [J{:}]')
0 comentarios
Ver también
Categorías
Más información sobre Data Type Conversion en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!