洛伦(Matlab)的艺术

将想法变成MATLAB

在非数字值上迭代

最近,一位同事希望编写一些代码以迭代结构中的字段。我至少可以想到三种不同的方式,有些比其他方式更直截了当。这就是我想到的。

内容

Create Data for an Example

I'm only going to consider scalar structures for this post. The contents of each field in this case will also be scalars, for easy illustration. I'd like to create output that increases the value of each entry by 1.

s.a = 1;s.b = 2;s.c = 3;

让我获取字段名称,以便我可以使代码合理通用。

fn = fieldnames(s)
fn ='a''b''c'

First Method - Loop Over Number of Field Names

In the first case, I find out how many fields are in the struct, and then loop over each of them, using dynamic field referencing to access the value in each field.

out1 =零(1,长度(fn));为了n = 1:长度(fn)out1(n)= s。(fn {n}) + 1;结尾out1
out1 = 2 3 4

第二种方法 - 循环在字段名称本身上

In the second case, I am going to bypass the numeric indexing and loop through the fields themselves. Since the为了MATLAB中的循环一次处理索引列一次,我必须将字段名称列转换为行矢量。它恰好是一个单元格数组,因此我还必须将字段名称转换为字符数组以使用动态字段引用。我不会预先分配输出out2this time, but allow this small array to grow, so I don't need to add a counter to the loop.

out2 = [];为了str = fn'out2(end + 1)= s。(char(str)) + 1;结尾out2
out2= 2 3 4

检查前两种方法的结果是否同意。

isequal(着干活,out2)
ans = 1

Third Method - Use structfun

而不是完全循环遍历字段,而是使用structfunwhich iterates over fields in a scalar structure.

out3 = structFun(@(x)x+1,s);out3 = out3。'
out3 = 2 3 4

由于结果是作为列向量返回的,因此我将它们转换为它们,因此我可以将输出与其他方法的输出进行比较。检查最后两种方法的结果是否同意。

que equal(out2,out3)
ans = 1

Which Way is Clearest?

我向您展示了三种迭代结构中字段的方法。您目前使用哪种方法?哪一个对您来说最清楚?让我知道here




以MATLAB®7.4出版

|

注释

To leave a comment, please clickhereto sign in to your MathWorks Account or create a new one.