2011-10-24 59 views
11

結構的多層次索引說在MATLAB我有以下:矢量在MATLAB

a(1).b.c = 4; 
a(2).b.c = 5; 
a(3).b.c = 7; 
.... 

我想收集的值[4 5 7 ...]在單個陣列中,而無需循環和在向量化方式。

我曾嘗試:

>> a(:).b.c 
# Error: Scalar index required for this type of multi-level indexing. 

>> a.b.c 
# Error: Dot name reference on non-scalar structure. 

,但他們沒有工作。我能想出的最好的是:

arrayfun(@(x) x.b.c, a); 

但據我瞭解arrayfunnot vectorized,是這樣嗎?

回答

1

a.b返回多個輸出,所以你不能指望調用它的功能。最好的一個班輪我能想到的,而無需使用arrayfun是:

y = subsref([a.b], substruct('.', c)); 

注意a.b.c實際上是相同的:

y = subsref(a.b, substruct('.', c)) 

這就是爲什麼它不應該對非標a工作。

2

您呼叫arrayfun似乎對Matlab來說足夠慣用。我不認爲這是矢量化的,但它是優化的,也許是最快的方法。 您還應該嘗試使用循環進行基準測試,以查看JIT編譯器在此處的性能是否良好。沒有測試就很難知道。

+0

'arrayfun'看起來好像沒什麼問題。 – Nzbuu

2

你可以做到這一點在兩行:

>> s = [a.b]; 
>> y = [s.c] 
y = 
    4  5  7 

另一種可能的一行(不易閱讀!):

>> y = squeeze(cell2mat(struct2cell([a.b]))) 
y = 
    4 
    5 
    7