Generate Code for transforming structure array to cell array
Show older comments
I have a structure array that I want to convert to a cell array. I can do this in MATLAB, but this function is part of a larger code base that I want to use in generated code. I'm struggling to get the cells extracted from the structure array into a cell array in such a way that is accetable for code generation. I've provided below the function that performs the transformation that I want in MATLAB, and a script that uses the function and tries to codegen it. I keep getting errors. Can someone help me generate code for this function or help me do the conversion in a better way that will work with MATLAB Coder? I'm new to MATLAB Coder, so I'm hoping this is something simple that I'm missing. Thanks!
Running the code in the question dialogue gives the wrong error. The corret error is: Directly accessing a field of a nonscalar struct is not supported for code generation. This limitation also applies to a property of a nonscalar object.
% This script calls the cellTform function and tries to generate code
% build the input struct array
StructIn(1).t = {magic(3)};
StructIn(2).t = {magic(3)};
StructIn(3).t = {magic(3)};
StructIn(4).t = {magic(3)};
StructIn(5).t = {magic(3)};
StructIn(6).t = {magic(3)};
% build the sorting index array
SortingInd = [1,3,2,5];
cellOut = cellTform(StructIn,SortingInd)
ARGS{1} = coder.typeof(StructIn,[Inf 1],[true false]);
ARGS{2} = coder.typeof(SortingInd,[Inf 1],[true false]);
codegen cellTform -args ARGS
function cellOut = cellTform(arrayStructIn,SortingIndexIn)
%#codegen
% This function accepts an array of strcuts that contain a {1x1} cell of
% [3x3] doubles and an array if indices that need to be extracted from the
% array of structs and put into the output cell of
% {1xlength(SortingIndexIn)}.
% Inputs:
% arrayStructIn = array of structs that contain a {1x1} cell of [3x3]
% doubles = arrayStructIn(N).t{1}[3x3]
% SortingIndexIn = column vector in indices that must be extracted from
% arrayStructIn [Mx1], not sorted and output cell must retain this order
% Output:
% cellOut = cell array {1xM} of the extracted cells of arrayStructIn
tdum = horzcat(arrayStructIn(:).t); % make a copy of the input structure
% cellOut = horzcat({tdum{SortingIndexIn}}); % extract the cells I want
% another way...
Nsort = length(SortingIndexIn);
cellOut = cell(1,Nsort);
for cnt = 1:Nsort
cellOut{cnt} = tdum{SortingIndexIn(cnt)};
end
end
1 Comment
Christopher Smith
on 1 Mar 2025
Answers (0)
Categories
Find more on MATLAB Coder in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!