Is there any alternative for goto-statements in MATLAB? - matlab

I have a problem with writing a program in MATLAB. I need a goto-statement for solving my problem. Here is the code:
for i=1:n
1: newT=T(i)+unifrnd(-r,r);
newT=P(i)+unifrnd(-r,r);
if newT<Tmax && newT>Tmin && newP<Pmax && newP>Pmax
bestT=newT bestP=newP
else
go to 1
end
end
Is there any alternative for that goto-statement?

Is something like this what you're looking for?
for i=1:n
loop = true;
while loop
newT=T(i)+unifrnd(-r,r);
newT=P(i)+unifrnd(-r,r);
if newT<Tmax && newT>Tmin && newP<Pmax && newP>Pmax
bestT=newT bestP=newP
loop = false;
end
end
end

You can use this submission at MathWorks ® : https://www.mathworks.com/matlabcentral/fileexchange/26949-matlab-goto-statement
However, I recommend you to modify your code instead of using that!

you can try switch-case method. Please see example below;
caseno = input('input your case no');
switch (caseno)
case 1
disp('this first section will run');
case 2
disp('this second section will run');
otherwise
disp('wrong case no');
end

Related

Ignore Condition on 1st Loop

if(Z1(m)<Z1(m-1)
IN=IN+1;
M1(:,IN)=Vb(:,t);
else
FCAST=Vb(N,T);
break;
end
I have this condition on my program, but the problem is it cannot work for first iteration because Z1(m)
Did anyone know how to solve this?
You can put the code you would like in the first iteration in it's own if statement
IF in == 1 || Z1(m)<Z1(m-1)
...
That might work.

How to move the control to the else part of "if-else" when error comes in the statements under 'if' part?

Is there a way to make condition such that if error comes in the statements/matrices under if then execute statements under else?
i.e .
if (some condition)
some statment1/matrix1/variable1
some statement2/matrix2/variable2
some statement3/matrix3/variable3
else newstatement/matrix %come to else part of the code if any of the statements 1,2 or 3 under if condition yields any error like dimension mismatch or anyother
end
No built-in mechanism to jump to else section. But you can use a construct like this:
condition_flag = (some condition);
error_flag = false;
if condition_flag
try
some statment1/matrix1/variable1
some statement2/matrix2/variable2
some statement3/matrix3/variable3
catch
error_flag = true;
end
end
if ~condition_flag || error_flag
%if any of the statements 1,2 or 3 under if condition yields any error like dimension mismatch or anyother
....
error_flag = false;
end
Alternative solution to the one of Mohsen Nostrania.
else_flag=true;
if (condition)
try
%% The if code
else_flag=false;
end
end
if else_flag
%% The else code
end
The else_flag=false; command is executed only when condition is true and no error occured within the <if code>.
Be aware that both solutions do literally what you want - the <if code> commands are executed until an error occur and then the <else code> is executed.
If one want to reduce tre number of if statements:
try
if statement
%% The if code
else
%% Obvious error
a(0);
end
catch
%% The else code
end

Combine isfield and ~isempty within the same test

I have written a lot of Matlab code using structs and I have the following problem recurring.
I often need to test if a field exists and is not empty. So far, my solution is:
if isfield(var, 'field')
if ~isempty(var.field)
...
when one or the other test fails I need to perform the very same action. In these cases the solution is far from being elegant. For example:
if isfield(var, 'field')
if ~isempty(var.field)
fieldOk = true;
else
fieldOk = false;
end
else
fieldOk = false;
end
A better solution would be to do both tests at once. I could write a function that wraps all this but I am wondering if there is a native Matlab solution.
What about:
if isfield(var, 'field') && ~isempty(var.field)
fieldOk = true;
else
fieldOk = false;
end
The logical operator X && Y just evaluates Y if X is true.
Have a look here. Therefore it's exactly what you need. But you may have to turn it around:
if ~isempty(var.field) && isfield(var, 'field')

Breaking out of recursive function calls in matlab

The following is only a simple example to generalize and illustrate the problem I am having.
If I have a function like the following:
function newtraph(initialguess,funct,dfunct)
ht = funct(initialguess);
if abs(ht) < 10^(-6)
disp(initialguess); return
elseif abs(ht) > 10^6
disp('Fix Guess'); return
end
newtraph(initialguess-(ht/dfunct(initialguess)), funct, dfunct);
The only way (that I am aware of) to exit out is through the use of those return statements. But, I want to assign output from functions of this variety to variables in the base workspace. I want to do some thing like:
function out = newtraph(initialguess,funct,dfunct)
ht = funct(initialguess);
if abs(ht) < 10^(-6)
out = initialguess; return
elseif abs(ht) > 10^6
disp('Fix Guess'); return
end
newtraph(initialguess-(ht/dfunct(initialguess)), funct, dfunct);
This doesn't work, the return prevents out from being assigned.
Output argument "out" (and maybe others) not assigned
Some ideas I have for a solution are using globals or evalin. But is there some simpler way that I am missing. I just want pass the output from functions of this style back to the base workspace?
A test case, just in case:
funct=#(x) -x-cos(x); dfunct=#(x) sin(x)-1; initialguess=1;
Thanks for your time.
Well, I am an idiot. It was simply a case of forgetting the final assignment:
function out = newtraph(initialguess,funct,dfunct)
ht = funct(initialguess);
if abs(ht) < 10^(-6) %Tolerance
out = initialguess; return
elseif abs(ht) > 10^6
out=0; return
end
out = newtraph(initialguess-(ht/dfunct(initialguess)), funct, dfunct);
Thanks for the quick help!
Your example function that doesn't work is almost there. You just need to assign
out = newtraph(...)
on the last line so you can capture the output.
You probably also need to assign out = 0 or some dummy value when you report "fix guess" so that branch of the code will also return a value.
Just a guess here: aren't you missing the assignment in the last line? And also don't you need to initialize out in your elseif in case out wasn't assigned before? I.e.
ht = funct(initialguess);
if abs(ht) < 10^(-6)
out = initialguess;
return
elseif abs(ht) > 10^6
disp('Fix Guess');
if ~exist('out')
out=1; % you need some default value if you ever reach this code without ever initializing out
end
return
end
out = newtraph(initialguess-(ht/dfunct(initialguess)), funct, dfunct);
This answer may be a little late, but I think that it is important enough to deserve to be pointed out here. To make the recursion clearer I do recommend another approach here.
function out = newtraph(initialguess,funct,dfunct,counter)
maxCount = % yourValue;
ht = funct(initialguess);
if abs(ht) > 10^(-6) || abs(ht) < 10^6 || counter<maxCount % Break out after x tries
counter = counter+1;
out = newtraph(initialguess-(ht/dfunct(initialguess)), funct, dfunct,counter);
elseif abs(ht) < 10^(-6) %Tolerance
out = initialguess;
else
warning('Convergence were not reached!');
out=0;
end
The preffered structure may be personal, but this way it is clear that you keep going until you hit a stop criterion, namely the function converged or were divergent.
Also, recursive functions are dangerous due to that the only way to stop them is to fulfill the exit criterion or when the program crashes. Matlab have a limit of how many times a recursion can go on and then throws an error. You will most likely want to handle the error by yourself (like you have done already by setting out=0;). Also matlabs limit is 500 recursive calls and you do most likely want to terminate the function earlier, maybe at 8-20 calls, depending on your algorithm.

How to avoid enter any i and j value when numeric input is required in matlab

Consider I have
a = input(value = );
how can I prevent user from enter i and j as the input values. I would like to have a code some thing like tat
if a == any value involves i and j
then break or terminate
and prompt the function a = input(value = ) again.
between I have tired something like this, but it doesn't work (the error is still coming out and it unable to prompt the second defined input a = input('enter again')), can anybody explain to me where's the mistake I have done.
if ~isnan(x) || ~isnumeric
a = input('enter again');
else
continue
end
I will really appreciate all the help.
Try the following to keep on pressing user to enter the values that abide by your conditions. As per my comment, the post gives a great idea of how you can achieve this. It is not using OR but AND to have a firm condional validation.
while ~(~isempty(a) ...
&& isnumeric(a) ...
&& isreal(a) ...
&& isfinite(a) ...
&& (a == fix(a)) ...
&& (a > 0))
a = input('Enter the number of dice to roll: ');
end
try this
a = NaN;
while isnan(a) || ~isreal(a)
a = input('value=','s');
a = str2double(a);
end