Reputation: 101
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.
Upvotes: 0
Views: 123
Reputation: 112769
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.
Upvotes: 2
Reputation: 13886
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.
Upvotes: 2