how to avoid using num2cell when dealing to structure arrays?

4 ビュー (過去 30 日間)
Angelos Vassiliou
Angelos Vassiliou 2012 年 8 月 27 日
I use a structure array, which contains a field i wish to manipulate for a subset of the structure array:
snr=[node.receivedSignal]./[node.receivedNoise]
temp=[node.power]
nodes_to_update=snr<threshold
newPower=temp(nodes_to_update)*2
at this point i have in my newPower array, (the power levels of the subset of nodes that i need to update). so far what i have been doing is the following:
X=num2cell(newPower)
[node(nodes_to_update).power]=deal(newPower)
Since this is in a loop that repeats too many times (simulation over time), i would like to avoid using num2cell and deal. i run the profiler, and these two functions are the major slowdown on my simulation.
is there a way of assigning values into a structure array's fields from a double array, without converting into a cell and then dealing it into the structure?
Working example:
a(1).a=3
a(2).a=3
a(3).a=5
b=[1 2]
the num2cell and deal solution:
x=num2cell(b)
[a([1 3]).a]=deal(x{:})
i am looking something in the spirit of:
[a([1 3].a]=deal(b(:))
  1 件のコメント
Matt Fig
Matt Fig 2012 年 8 月 27 日
I get an error when I use your example.
Assignment between unlike types is not allowed.

サインインしてコメントする。

採用された回答

Matt Fig
Matt Fig 2012 年 8 月 27 日
There is a way to do it, and it will be faster (at least it is here):
for ii = 1:length(b)
a(idx(ii)).a = b(ii);
end
idx is the [1 3] in your example. For large structures and large index vectors, this will be more than twice as fast.
  2 件のコメント
Jan
Jan 2012 年 8 月 28 日
And pre-allocate "a" e.g. by running the loop over length(b):-1:1.
Angelos Vassiliou
Angelos Vassiliou 2012 年 8 月 28 日
Thank you Matt, i fixed the question, and i will implement your suggestion. Preliminary results show an 87% reduction in time (on the time spent by num2cell and deal). I would just think that using the official MATLAB vectorized function would yield better result than a loop around the structure.

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2012 年 8 月 27 日
No, there is not.
Note: your deal solution is not correct. You need to adjust to
[a([1 3]).a] = deal(x{:})
which can be abbreviated to
[a([1 3]).a] = x{:};
However, the num2cell() step is required, as is assigning the result to a variable.
  1 件のコメント
Angelos Vassiliou
Angelos Vassiliou 2012 年 8 月 28 日
Thank you for you comment, i fixed the original post. By the way, just by removing the deal from the expression actually halved the time that the command took to execute. Now if only num2cell could also have been sidestepped...

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeClocks and Timers についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by