How to get rid of the for loop ?

2 views (last 30 days)
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 ?

Accepted Answer

Kelly Kearney
Kelly Kearney on 9 Sep 2015
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 Comments
per isakson
per isakson on 9 Sep 2015
... 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 on 10 Sep 2015
Thank you very much, both of you. Helps a lot!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!