Converting 1x1 struct with multiple fields to numeric matrix

50 views (last 30 days)
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 Comment
Matt J
Matt J on 27 Nov 2024 at 15:10
containing either a single number or a cell array.
I don't see numbers and cell arrays. I see numbers and char vectors

Sign in to comment.

Accepted Answer

Epsilon
Epsilon on 27 Nov 2024 at 15:20
Edited: Epsilon on 27 Nov 2024 at 15:20
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);
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
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!

More Answers (1)

Matt J
Matt J on 27 Nov 2024 at 15:20
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{:}]')
result = 5×6
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
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!