Streamlining Code for Efficiency

1 view (last 30 days)
eugene479
eugene479 on 17 Mar 2016
Commented: eugene479 on 18 Mar 2016
Hi all,
Was wondering if there's any way to make this code run faster. This is just a snapshot of the code:
  • I have an array y of size (e.g. 63 rows, 6 columns) made up of just 1s and 0s.
  • I'm applying some logical constraints (> 20) to it (termed as "LogicT")
  • I've put the logic test within the "for" loop, but am wondering how I can place it outside the "for" loop for faster run time (e.g. specifying "i" as a variable?)?
for i = 1:size(y,1)
LogicT{1} = (y(i,1)+ y(i,2)) <=1;
LogicT{2} = y(i,2) == y(i,6);
LogicT{3} = 1 - y(i,3) + y(i,1) + y(i,2)>= 1;
if LogicT{1} == 1 && ...
LogicT{2} == 1 && ...
LogicT{3} == 1
TotalNew(i,:) = y(i,:);
else TotalNew(i,:) = zeros(1,size(y,2));
end
end
Many thanks in advance for your help. And apologies if this is a trivial question.
Best regards, Eugene

Accepted Answer

Roger Stafford
Roger Stafford on 17 Mar 2016
TotalNew = bsxfun(@times,(y(:,1)+y(:,2)<=1)&(y(:,2)==y(:,6))&(1-y(:,3)+y(:,1)+y(:,2)>=1),y);
  1 Comment
eugene479
eugene479 on 18 Mar 2016
Perfect! Works like a charm. Thank you so much!

Sign in to comment.

More Answers (0)

Categories

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

Community Treasure Hunt

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

Start Hunting!