0

I have a big code but i want to make a for loop to execute the code.My code is below:

A = zeros(1, 60) ; C = A ; D = A ; F = A ; ....... if( sum(B) == 100 ) A= A(1) + 1; elseif( sum(B) == (99) ) C(1) = C(1) + 1; elseif( sum(B) == (98) ) D(1) = D(1) + 1; elseif( sum(B) == (97) ) E(1) = E(1) + 1; ......... end O1=A; O2=C; O3=D; O4=F; O=[O1,O2,O3,O4] 

I need to check upto sum(B)==1 so its looks worse if i write the whole condition using elseif so i want to use a for loop to execute this condition.But i cant do this.

Matlab experts needs your valuable sugggestion and help.

1
  • 1
    Check link Commented Oct 1, 2013 at 10:11

2 Answers 2

2

How about something like:

A = zeros(100,60); for k=100:-1:1 if sum(B) == k A(101-k,1) = A(101-k,1) + 1; end end 

Note that it's never a good idea to do equality tests on floating point numbers though, better to compare the difference to a small tolerance value.

Sign up to request clarification or add additional context in comments.

1 Comment

You don't really need a for loop. You can do something like: k = sum(B); if (k>=1 & k<=100), A(101-k,1) = A(101-k,1) + 1;, end
2

If would be better to replace A, B, C... by a cell array: X{1}, X{2}, X{3},...:

X = cell(1,100); % change "100" as needed [X{:}] = deal(zeros(1,60)); % initialize each cell as needed X{101-sum(B)}(1) = X{101-sum(B)}(1) + 1; % or whatever operation is required here 

If all your former A, B, C, ... have the same size, you can use an array instead of a cell array.

2 Comments

Nice. Same idea as my answer, without a for loop.
I just wrote in your answer about not needing a loop :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.