MATLAB Function에서 struct의 배열 별 요소 개수 구하기

3 次查看(过去 30 天)
MATLAB Function에서 arr의 struct 배열 개수, 배열 별 요소의 개수를 구하고 출력하고 싶습니다.
배열 별 요소 개수를 구하기 위해 cell_num을 구현했는데 적절한가요? 또한, 출력하려면 어떻게 해야 하나요?
cell_num = struct();
arr = struct("sig1",{{1,2,3,4}},"sig2",{{4,5,6}},"sig3",{{7,8}});
sig_num = 3;
for i = 1:sig_num
cell_num = structfun(@size,arr,"UniformOutput",false);
y = cell_num(i);
end

采纳的回答

Dyuman Joshi
Dyuman Joshi 2023-9-20
%Defining structure
cell_num = struct();
arr = struct("sig1",{{1,2,3,4}},"sig2",{{4,5,6}},"sig3",{{7,8}})
arr = struct with fields:
sig1: {[1] [2] [3] [4]} sig2: {[4] [5] [6]} sig3: {[7] [8]}
%Field names of the structure arr
names = fieldnames(arr)
names = 3×1 cell array
{'sig1'} {'sig2'} {'sig3'}
%Number of fields in arr
n = numel(names)
n = 3
%Number of elements in each field
y = structfun(@numel,arr)
y = 3×1
4 3 2
To display or printf -
%Method 1
disp(y)
4 3 2
%Method 2
fprintf('%d\n',y)
4 3 2
  2 个评论
eblee
eblee 2023-9-21
a = structfun(@numel,arr,UniformOutput=false);
fprintf('%d\n',a);
Running on the MATLAB Function results in an 'An input argument with type 'struct' is inconsistent with the conversion character 'd' in the 'formatSpec'.' error.
Is there any way to output a structure from the MATLAB function?
Dyuman Joshi
Dyuman Joshi 2023-9-21
There is no need to use UniformOutput=false for the structfun command.
You can see that I have not used that in my code above.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 구조체 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!