Converting 1x1 struct with multiple fields to numeric matrix

26 次查看(过去 30 天)
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 个评论
Matt J
Matt J 2024-11-27
containing either a single number or a cell array.
I don't see numbers and cell arrays. I see numbers and char vectors

请先登录,再进行评论。

采纳的回答

Epsilon
Epsilon 2024-11-27
编辑:Epsilon 2024-11-27
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!

更多回答(1 个)

Matt J
Matt J 2024-11-27
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>

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by