Matlab loops in loop - matlab

For this loop in MATLAB, after the 'if - end' I want to return to the same loop without executing next i. More specifically, I want to tell MATLAB to check until check(i) is different from 0.
for i = 1:length(numDate)
check(i)=any(Dates == numDate(i));
if check(i) == 0
numDate(i) = numDate(i)-1;
end
end

You cannot change the number of iterations of a for loop once it is decided. Use while loop for such a case.
k=1; %I replaced the loop variable with k because i (and j) are reserved for imag no.s
while k<=length(numDate)
if any(Dates == numDate(k)) == 0
numDate(k) = numDate(k)-1;
else k=k+1; %increment only if the condition is not satisfied
end
end

Use break
for i = 1:length(numDate)
check(i)=any(Dates == numDate(i));
if check(i) == 0
numDate(i) = numDate(i)-1;
else
break
end
end

Related

Matlab symbols used to terminate the loop

I am new to matlab and I have couple of questions about it. First one, "Your function should terminate the sequence when either the value of ... or..." I use || in the code but it does not work as expected while && gives me the correct answer. Second question, how could the code be to display only the final answer?
Problem: calculate X which is represented by the sequence below
X = 1 - 1/2^2 + 1/3^2 - 1/4^2 +....
Requirement: Your function should terminate the sequence when either the value of 1/k^2 is less than 0.0001 or k is equal to k_max.
input k
Initialize x = 0
for loop i from 1 to k
if 1/i^2<0.0001 && i >= 100
break
end
Calculate X = (-1)^(i+1)./i^2 + X
end
You can use the break function as follows, where END_CONDITION is the condition you want to end your loop in.
if END_CONDITION
disp(X);
break;
end
To display the final answer, you can use the disp function. Eg. if your variable you want to print is called A then you use the following code.
disp(A)
Collectively this is your code. Since k_max terminates at the end of the for loop, we don't have to add any conditions to break out of the loop.
X = 0;
for i = 1:k
if 1/i^2<0.0001 || i==100
break;
end
X = (-1)^(i+1)./i^2 + X;
end
disp(X);

get around using break or return statements

I am using Matlab to modify some code that will be used in a real time system. The real time system can't use 'break' or 'return' statements. I have a bunch of for loops in Matlab that use 'break' or 'return'.
This is an example:
for j = find(vec == 0)
if A(j) == 1
break;
end
end
How do I get around using the 'break' statements? I was told that I can use a 'while' loop instead. however, I am trying to see if there are other ways.
This seems like it should be a basic question but I can't think of other solutions right now.
A for with break is equivalent to a while.
for jj = find(vec == 0)
if A(jj) == 1
break;
end
end
....
ind = find(vec == 0);
p = 1;
while ( A(ind(p)) ~= 1 && p<length(ind) )
p = p+1;
end
p = ind(p);
bonus: using i and j is bad: Using i and j as variables in Matlab

Exit loop at the end of current iteration step if condition is fulfilled

A common problem I have is the following:
Within a loop (usually a for loop) some constraints are - and have to be - checked at the beginning. Now sometimes if a condition if fulfilled, the code within the loop should run to the end of the current iteration step and then quit.
Usually I'd do it somehow like so
a = 0;
quit = 0;
for i = 1:1:11
if (a == 5) % Condition to be checked *before* the calculation
quit = 1; % Stop loop after this iteration
end
a = a + 1; % Calculation
...
if (quit == 1)
break;
end
end
But in a tight loop already this extra condition checking if (quit == 1) might give a relevant slow down. Also one needs to introduce an extra variable so I wonder how this is usually done or if there is a better way to do it...
why not do this way.
for i = 1:1:11
if (a == 5) % Condition to be checked *before* the calculation
func() --> do all the calculations
break; % Stop loop after this iteration
else
func() --> do all calculations
end
end
function func()
a = a+1
//all other calculations
end
Normally you can detect when to stop iterating. But if I understand your question, you can only detect when it should be the last iteration. You could try this:
a = 0;
i = 1;
while (i<=11)
if (a == 5)
i = 12; % Make sure this is the last iteration
else
i = i + 1;
end
a = a + 1;
end
What about:
for i = 1:11
quit = (a==5); % Condition to be checked *before* the calculation
a = a+1
if quit
break; % Stop loop after this iteration
end
end
Makes any difference?
- Make an infinite loop with logical variable condition set to 1
- Within the loop when stopping loop criteria rises set the logical
variable condition to 0
- loop will no longer run
count = 0;
stop = 11;
condition = 1;
while condition
count = count + 1;
--> do all the calculations before checking
condition = ~(a == 5 || count == stop);
--> do all the remaining calculations then exit from the loop
end
The while loop is enough
a = 0;
quit = 0;
while (a <= 5)
a++; % Calculation
...
end

Identifying a flag set and printing a message in Matlab

Hi all I am working on checking for certain cases in a large loop, with in this large loop is this statement:
%Center Dialouge
timers_c = [start_dpc_sh_hi_timer_c, start_dpc_sh_lo_timer_c, start_ffm_sh_act_hi_timer_c,...
start_ffm_sh_act_lo_timer_c, start_hpot_eff_loss_timer_c, start_lfpt_dpsh_timer_c,...
start_pc_sh_time_c, start_post_tl_nl_c, start_pre_tl_nl_c, start_elec_lu_timer_c];
if perf_case_c ~= -1
for k = 1:10
if iscellstr(timers_c(k)) == 1
perf_case_timer_c = timers_c{k};
timer_set_c = 1;
end
end
end
To I identify the start time and the case type to be output in a dialogue message:
if timer_set_c == 1
pcase_c = msgbox([sprintf('%s'),perf_case_c,sprintf('\nMET:%s\n'),perf_case_timer_c],'PERFORMANCE CASE');
end
I can't get the if statement that determines which case has been determined to work. I am trying to use the change from -1 to a string somehow, but it doesn't quite work.
A minimal example would be
%Assume all timers initialized as zero
%Assume case ~= -1 (is a char array, string
timers_c = [timer1, timer2, timer3 ]
if case ~= -1
for k = 1:3
if iscellstr(timer_c(k)) ==1
case_time = timers(c{k});
time_set_flag = 1
end
end
end
...
and then outside of the loop would be the above msgbox

Using fprintf to print on several lines in Matlab

Question:
Write a procedure called Print7 to print all integer numbers within the range 0:100 that are divisible by 7. Ten numbers are to be printed on one output line. Hence write a program that invokes that procedure.
This is what I did
file = fopen('print7.dat','r');
x = 1:100
for x=[1:100]
if mod(x,7) == 0;
print7 = [x]
end
end
fprintf('print7 %d\n', print7)
Now it's output becomes the number 98 - which I understand to be the largest number under 100 divisible by 7. But I want a 10xn matrix-like result.
What do I do?
What you are doing stores your result in a variable and overwrites the variable in each iteration. You could print it directly instead like this:
c=0;
for x=[1:100]
if mod(x,7) == 0
fprintf('%3d',x)
c=c+1;
if mod(c,10) ==0
fprintf('\n')
end
end
end
fileID = fopen('print7.dat','r');
for x = 1:100
if(mod(x,7) == 0)
fprintf(fileID,'%d',x);
end %end of if
end %end of for
fclose(fileID);