Matlab Iteratively remove a row of matrix, except for first iteration - matlab

I have a matrix that I use to solve a system of equation using ode45. I am iteratively removing one row in a while loop. However, I want the first iteration to 'continue' and not remove any arrow, so that I can compare all my results where one array is removed with the result using initial matrix.
It would look like:
while smtg
A(pos,:)=0 % Do not compute this line the first iteration
pop=ode45(involving A)
end
My real code:
countrow=0;
A=randi([0 1], 5, 5);
distrib=sum(A,1);
while sum(distrib)>5
countrow=countrow+1;
A(pos,:)=0; % remove one row
options = odeset('RelTol', 1e-4);
[t, pop]=ode45(#Diff,[0 MaxTime],[E I],options,n,m, A);
nbtot =sum(pop(:,n+1:2*n),2);
end
I tried to use
if countrow==1 % (the first iteration),
continue;
end
but it skips until the second end and not compute nbtot so I'm out of ideas... Any help?

If you don't want A(pos,:)=0; % remove one row to occur on the first iteration then put it inside an if statement like
countrow = countrow + 1;
if countrow ~= 1
A(pos,:)=0; % remove one row
end
The ~= symbol in MATLAB is "not equal to". The line A(pos,:)=0; % remove one row will now only execute when countrow is not equal to 1 but all of the other statements within the loop will execute as normal.
The keyword continue will stop the execution of the current loop iteration and proceed to the next loop iteration. All of the statements after a continue within a loop will not be executed.

Or you can go with :
A(pos,:)=A(pos,:)*(countrow==1);

Related

How to jump to a particular place in the for loop if the if condition is satisfied?

I have some image files. I'm trying to perform some calculations using each file and if a certain condition is met, I'd like to go back to a particular line in the code and run it from there once more. But only just once again. Regardless of whether the if condition is satisfied or not satisfied the second time, I want to go to the next iteration. But, MATLAB doesn't seem to have a goto function and also, using goto implies bad programming so I thought I'd just iterate the for loop twice for a particular 'i' value which satisfies the if condition.
file = dir('*.jpg');
n = length(file);
for i = 1:n
*perform some operations on the 'i'th file*
if 'condition'
*run the for loop again for the 'i'th file instead of going to the 'i+1'th file*
i=i-1;
else
*go to next iteration*
end
end
I have tried to code this by changing the loop variable 'i' inside the loop to 'i-1' so that on the next iteration, the 'i'th loop will be repeated again but doing so is giving the wrong output, though I don't know if there is some other error in my code or if the changing of the loop variable internally is the cause of the problem. Any help on this is appreciated.
Replace the for loop with a while loop to have a bit more flexibility. The only difference is that you have to manually increment i, hence this also allows you to not increment i.
Given your new requirement, you can keep track of the number of attempts, and easily change this if needed:
file = dir('*.jpg');
n = length(file);
i = 1;
attempts = 1;
while i <= n
% perform code on i'th file
success = doSomething(); % set success true or false;
if success
% increment to go to next file
i = i + 1;
elseif ~success && attempts <= 2 % failed, but gave it only one try
% increment number of attempts, to prevent performing
attempts = attempts + 1;
else % failed, and max attempts reached, increment to go to next file
i = i + 1;
% reset number of attempts
attempts = 1;
end
end
Given the new requirement, added after rinkert's answer, the simplest approach becomes separating out code from your loop in a separate function:
function main_function
file = dir('*.jpg');
n = length(file);
for i = 1:n
some_operations(i);
if 'condition'
some_operations(i);
end
end
function some_operations(i)
% Here you can access file(i), since this function has access to the variables defined in main_function
*perform some operations on the 'i'th file*
end
end % This one is important, it makes some_operations part of main_function

How to restart a for loop iteration in MATLAB?

I am trying to force a for loop to restart if a condition is not stratified. I can do it with while since I want the loop to run for a certain number of iterations. I tried to set iter=iter-1 inside the if statement but it did not work. Any suggestions?
R=2*10^3;
lamda= 0.00001;
h=100;
a = 9.6117;
b = 0.1581;
for iter=1:10
M=poissrnd(lamda*R^2);
xx=R*rand(1,M);
yy=R*rand(1,M);
zz=ones(1,M)*h;
BS=[xx' yy' zz'];
user=[0,0, 0];
s=pdist2(BS(:,1:2),user(1,1:2));
anga=atand(h./s);
PL=1./(1+(a*exp(b*(a-anga))));
berRV=binornd(1,PL);
if berRV(1)==1
% do something
else
% repeat
end
end
You can accomplish this by using a while loop, with a comparison to whether the number of needed results have been identified. See the comment about saving your found values, as you hadn't specified what needs to be done when the condition you're searching for is satisfied.
R=2*10^3;
lamda= 0.00001;
h=100;
a = 9.6117;
b = 0.1581;
total_results_found = 0;
needed_results_found = 10;
while total_results_found < needed_results_found
M=poissrnd(lamda*R^2);
xx=R*rand(1,M);
yy=R*rand(1,M);
zz=ones(1,M)*h;
BS=[xx' yy' zz'];
user=[0,0, 0];
s=pdist2(BS(:,1:2),user(1,1:2));
anga=atand(h./s);
PL=1./(1+(a*exp(b*(a-anga))));
berRV=binornd(1,PL);
if berRV(1)==1
% save the result here
% iterate the counter
total_results_found = total_results_found + 1;
end
end
The simplest approach here would be with a while loop inside the for loop:
for iter=1:10
berRV(1) = 0
while berRV(1)~=1
% original loop code here
end
% do something
end
[Sadly, MATLAB does not have a do...while loop, it would make the above a little cleaner.]
While the other two solutions are perfectly valid, I wanted to give you another solution, which I think is the closest to the logic you provided in the question.
for iter=1:10
while 1
% loop code here
if berRV(1) == 1
break
end
end
end
The idea is similar to the one Cris presents, namely that you repeat the body of the for-loop until some condition is met. The difference lies solely in how you terminate the while loop,

MATLAB Cycle through vector values sequentially in a large for Loop

I have a small vector that has values that need to be calculated in sequence while a large for loop executes. Each time the for loop executes, it sequentially moves from vector index 1 to end then reset until the for loop executes completely.
For example, if the vector is [4 2 1] and the for loop executes n times, the index value will be 4,2,1,4,2,1,4,2,1... etc.
I was wondering if there was a way to optimize or shrink some code I developed or even if there was another way to accomplish the task, simpler or not.
Here's my code:
cookie_jar = [prt/4 prt/2 prt];
...
for k = 1:reps;
if k <= length(cookie_jar);
cookie = cookie_jar(k);
elseif rem(k,length(cookie_jar)) == 0
cookie = cookie_jar(end);
else
cookie = cookie_jar(rem(k,length(cookie_jar)));
end
end
Thanks!
You have to fix the third case to match indexing which starts with 1, then the first two cases are no longer required:
for k = 1:reps
cookie=cookie_jar(rem(k-1,length(cookie_jar))+1)
%...
end

continue statment not executing correctly within for loop+matlab

I have the following code:
for i=1:length(files)
for j=1:length(files(i,1).day)
if ((1:length(files(i,1).day(j).hour)) ~= 24)
continue
end
for h = 1:24
if ((1:length(files(i,1).day(j).hour(h).halfhour)) ~= 2)
continue
end
if isempty(1:length(files(i,1).day(j).hour))
continue
end
dayPSD = [];
for h2=1:2
dayPSD = [dayPSD; files(i,1).day(j).hour(h).halfhour(h2).data{8}'];
end
end
end
end
where
files=1x3 structure
files(i,1).day=1x335 structure that contains 1 field hour which is a 1x24 structure
files(i,1).day.hour=1x24 structure that contains 1 field halfhour which is a 1x2 structure
I am trying to loop through i and j, but when 1:length(files(i,1).day(j).hour) ~= 24 (so when the hours are less than 24) I would like to exit the loop and continue onto the next iteration of the for loop. I would also like it to exit the loop and continue onto the next iteration of the for loop if 1:length(files(i,1).day(j).hour(h).halfhour) ~= 2 (so when the half hours are less than 2) or if 1:length(files(i,1).day(j).hour is an empty cell (no data).
The current code I have written only seems to skip a loop index if 1:length(files(i,1).day(j).hour ~=24.
What am I doing wrong? Also how do I get it to continue onto the next iteration if any of those conditions are met? I've been banging my head on this for a while, and I know I'm probably making a simple mistake, but if anyone can point me in the right direction that would be great.
Thanks for your help in advance!
If I understand correctly, what you want is:
for i=1:length(files)
for j=1:length(files(i,1).day)
if ((1:length(files(i,1).day(j).hour)) ~= 24)
continue
end
for h = 1:24
if ((length(files(i,1).day(j).hour(h).halfhour)) ~= 2)
break
end
if isempty(files(i,1).day(j).hour)
break
end
dayPSD = [];
for h2=1:2
dayPSD = [dayPSD; files(i,1).day(j).hour(h).halfhour(h2).data{8}'];
end
end
end
end
so when either condition is met, the flow of execution will exit the for h=.. loop, and as there is no other statement in the for j=1... loop, the code will in effect skip that iteration.
Also note that if ((1:length(files(i,1).day(j).hour(h).halfhour)) ~= 2) is comparing a vector (1:length(..)) to a scalar 2 which results in a vector of booleans. The if part will only be executed if all its elements are true which is most likely never the case.

How to count the number of iterations

I'm working with k-means on MATLAB. To process the valid cluster, it needs to do a looping until the cluster position doesn't change any more. The looping will show the iterations process.
I want to count how many looping/iteration happens on that clustering process. Here is the snippet of looping/iteration processing part:
while 1,
d=DistMatrix3(data,c); %// calculate the distance
[z,g]=min(d,[],2); %// set the matrix g group
if g==temp, %// if the iteration does not change anymore
break; %// stop the iteration
else
temp=g; %// copy the matrix to the temporary variable
end
for i=1:k
f=find(g==i);
if f %// calculate the new centroid
c(i,:)=mean(data(find(g==i),:),1);
end
end
end
All I know that I have to do is define the iteration variable, and then write the calculation part. But, where do I have to define the variable? And how?
All the answers will be so much appreciated.
Thank you.
A Matlab while-loop is executed until the expression is false. The general setup is like this:
while <expression>
<statement>
end
If you want to count the number of times the while loop was entered, the easiest way is to declare a variable outside the loop and incrementing it inside:
LoopCounter = 0;
while <expression>
<statement>
LoopCounter = LoopCounter + 1;
end
The question whether to increment the LoopCounter before or after the <statement> depends on whether you need it to access vector entries. In that case, it should be incremented before the <statement> because 0 is not a valid index in Matlab.
Define before your loop, update in your loop.
iterations=0;
while 1,
d=DistMatrix3(data,c); % calculate the distance
[z,g]=min(d,[],2); % set the matrix g group
if g==temp, % if the iteration doesn't change anymore
break; % stop the iteration
else
temp=g; % copy the matrix to the temporary variable
end
for i=1:k
f=find(g==i);
if f % calculate the new centroid
c(i,:)=mean(data(find(g==i),:),1);
end
end
iterations=iterations+1;
end
fprintf('Did %d iterations.\n',iterations);