How to get rid of the for loop ?

1 回表示 (過去 30 日間)
Robert Thiel
Robert Thiel 2015 年 9 月 9 日
コメント済み: Robert Thiel 2015 年 9 月 10 日
the task
handles.plotdata.IR1 = zeros(1, 2001);
handles.plotdata.IR2 = zeros(1, 2001);
handles.plotdata.ax = zeros(1, 2001);
handles.plotdata.ay = zeros(1, 2001);
handles.plotdata.az = zeros(1, 2001);
my simplification so far
Kanal_name = {'IR1' 'IR2' 'ax' 'ay' 'az'};
for n = 1:length(Kanal_name)
handles.plotdata.(Kanal_name{n}) = zeros(1, 2001);
end
now i want to get rid of the for loop, any suggestions ?
  1 件のコメント
James Tursa
James Tursa 2015 年 9 月 9 日
Why do you want to get rid of the loop?

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

採用された回答

Kelly Kearney
Kelly Kearney 2015 年 9 月 9 日
Maybe this?
tmp = cell(2,length(Kanal_name));
tmp(1,:) = Kanal_name;
[tmp{2,:}] = deal(zeros(1,2001));
handles.plotdata = struct(tmp{:});
But this makes the code more difficult to read without adding any real benefit that I can see (the time difference is pretty negligible). Unless you have a definitive need to eliminate loops, I'd stick with your version.
  2 件のコメント
per isakson
per isakson 2015 年 9 月 9 日
... or this
>> clear all
>> handles.plotdata = cell2struct( repmat({zeros(1, 2001)},1,5) ...
, {'IR1' 'IR2' 'ax' 'ay' 'az'}, 2 );
>> handles.plotdata
ans =
IR1: [1x2001 double]
IR2: [1x2001 double]
ax: [1x2001 double]
ay: [1x2001 double]
az: [1x2001 double]
Robert Thiel
Robert Thiel 2015 年 9 月 10 日
Thank you very much, both of you. Helps a lot!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by