在MATLAB中动态读取数组中的多个值

时间:2022-11-29 20:51:32

I have an array of structures.
I'm trying to select several records from the array, that match some condition.
I know there's this option: (For example array A with field f1):

我有一系列结构。我正在尝试从数组中选择几个符合某些条件的记录。我知道有这个选项:(例如阵列A,字段为f1):

A([A.f1]==5) 

Which would return all the records that have f1 = 5.
But I want to do it for several different fields, in a loop. I saved the fields names in a cell array, but I don't know how to do the same with a dynamic field name.
I know there's the 'getfield' function, but it only selects a field from a single structure.
Is there a way to do it?
Thanks!

哪个会返回所有f1 = 5的记录。但是我想在循环中为几个不同的字段做这个。我将字段名称保存在单元格数组中,但我不知道如何使用动态字段名称执行相同的操作。我知道有'getfield'功能,但它只从单个结构中选择一个字段。有办法吗?谢谢!

2 个解决方案

#1


3  

To access dynamically a field of a structure:

要动态访问结构的字段:

% Create example structure
s.a = 1;
s.b = 2;

% Suppose you retrieve the fieldnames (or hardcode them fnames = {'a','b'})
fnames = fieldnames(s);

The you can retrieve e.g. the second one:

您可以检索,例如第二个:

s.(fnames{2})

In a loop

在循环中

for f = 1:numel(fnames)
    s.(fnames{f})
end

In your case:

在你的情况下:

A([A.(fnames{ii})] == n)

#2


-1  

This code will run through the first 5 records of your dynamical names

此代码将贯穿您的动态名称的前5个记录

for i=1:5
   eval(['A([A.' cell_array{i} ']==5)'])
end

#1


3  

To access dynamically a field of a structure:

要动态访问结构的字段:

% Create example structure
s.a = 1;
s.b = 2;

% Suppose you retrieve the fieldnames (or hardcode them fnames = {'a','b'})
fnames = fieldnames(s);

The you can retrieve e.g. the second one:

您可以检索,例如第二个:

s.(fnames{2})

In a loop

在循环中

for f = 1:numel(fnames)
    s.(fnames{f})
end

In your case:

在你的情况下:

A([A.(fnames{ii})] == n)

#2


-1  

This code will run through the first 5 records of your dynamical names

此代码将贯穿您的动态名称的前5个记录

for i=1:5
   eval(['A([A.' cell_array{i} ']==5)'])
end