通过字段名称和一些非顺序索引选择结构元素 [英] Pick a struct element by field name and some non-sequential index

查看:57
本文介绍了通过字段名称和一些非顺序索引选择结构元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是使用结构来保存表格":

I mean to use a struct to hold a "table":

% Sample data
% idx  idxstr  var1  var2  var3
%   1    i01    3.5  21.0   5
%  12    i12    6.5   1.0   3

第一行包含字段名称.假设我创建了一个结构

The first row contains the field names. Assume I created a struct

ds2 = struct( ...
    'idx', { 1, 12 }, ...
    'idxstr', { 'i01', 'i12' }, ...
    'var1', { 3.5, 6.5 }, ...
    'var2', { 21, 1 }, ...
    'var3', { 5, 3 } ...
);

如何检索字段 var2 的值,对应于 idxstr 的行等于 'i01'?

How can I retrieve the value for field var2, for the row corresponding to idxstr equal to 'i01'?

注意事项:

  1. 我无法确保 idxstr 元素的长度始终为 3.
  2. 理想情况下,我会有一种方法也适用于包含字符串或任何其他类型变量的列 var2.
  1. I cannot ensure the length of idxstr elements will always be 3.
  2. Ideally, I would have a method that also works for columns var2 containing strings, or any other type of variable.

PS:我认为 https://stackoverflow.com/a/35976320/2707864 可以提供帮助.

PS: I think https://stackoverflow.com/a/35976320/2707864 can help.

推荐答案

假设 idxstr 可以超过 3 个字符(有一个较短的版本,它总是 3 个字符),就是这样我想出了(在 MATLAB 上测试):

Assuming that idxstr can be more than 3 characters (there is a shorter version of its always 3 chars), this is the thing I came up with (tested on MATLAB):

logical_index=~cellfun(@isempty,strfind({ds2(:).idxstr},'i01'))

您可以通过以下方式访问变量:

you can access the variables as:

ds2(~cellfun(@isempty,strfind({ds2(:).idxstr},'i01'))).var2;
% using above variable
ds2(logical_index).var2;

现在你可以理解为什么 MATLAB 会引入表格了,呵呵.

You can understand now why MATLAB introduced tables hehe.

这篇关于通过字段名称和一些非顺序索引选择结构元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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