在MATLAB中遍历结构字段名

在MATLAB中遍历结构字段名

本文介绍了在MATLAB中遍历结构字段名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很容易概括为:为什么以下内容不起作用?"

My question is easily summarized as: "Why does the following not work?"

teststruct = struct('a',3,'b',5,'c',9)

fields = fieldnames(teststruct)

for i=1:numel(fields)
  fields(i)
  teststruct.(fields(i))
end

输出:

ans = 'a'

??? Argument to dynamic structure reference must evaluate to a valid field name.

特别是因为teststruct.('a') 确实起作用.然后fields(i)打印出ans = 'a'.

Especially since teststruct.('a') does work. And fields(i) prints out ans = 'a'.

我无法解决这个问题.

I can't get my head around it.

推荐答案

由于 fieldnames 函数返回单元格数组:

for i = 1:numel(fields)
  teststruct.(fields{i})
end

使用括号访问您的单元格数组将仅返回另一个单元格数组,其显示方式与字符数组不同:

Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:

>> fields(1)  % Get the first cell of the cell array

ans = 

    'a'       % This is how the 1-element cell array is displayed

>> fields{1}  % Get the contents of the first cell of the cell array

ans =

a             % This is how the single character is displayed

这篇关于在MATLAB中遍历结构字段名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 11:15