在 MATLAB 中遍历结构体字段名 [英] Iterating through struct fieldnames in MATLAB

查看:50
本文介绍了在 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'.

我无法理解它.

推荐答案

你必须使用花括号 ({}) 来访问 fields,因为 fieldnames 函数返回一个 元胞数组 字符串:

You have to use curly braces ({}) to access fields, since the fieldnames function returns a cell array of strings:

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 中遍历结构体字段名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆