How to avoid enter any i and j value when numeric input is required in matlab - 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

Related

MATLAB String Input If statment

I'm trying to make a program that asks a yes or no question. Based on that answer the program will continue or terminate. I keep getting an error since the arrays don't have the same dimension. I tried to use strcmp() but failed. I don't understand how true or false will help me discriminate between different words and capitalization. (Do I have to test each letter?) I want the program to continue if the input is any of these words 'yes','YES','Yes','y' and quit if the input is 'no','NO','No','n' I really want to understand, the == feels wrong somehow.
Thank You
ZZ=input('Do you want to know when you''ll turn 100?: ', 's');
NN={'no','NO','No','n'}
YY={'yes','YES','Yes','y'}
XX=strcmp(ZZ(NN),ZZ(YY)); %I thought this line would let MATLAB know everything is ok
if ZZ=='no' || ZZ=='NO' || ZZ=='No' || ZZ=='nO' || ZZ=='n'
disp('Thank You.')
disp('Come again.')
elseif ZZ=='yes' || ZZ=='YES'|| ZZ=='Yes'|| ZZ=='y'
x=input('Enter your age: '); %x is your age.
.....
I think if you need your program to run more than once, you need a for or while loop.
zz = 'yes';
while strcmpi(zz(1),'y')
x = input('Enter your age: ');
zz = input('Do you want to know when you''ll turn 100?: ', 's');
end

Is there any alternative for goto-statements in 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

Matlab Create an array with element of a for loop

Here's my code:
N = 1:999;
for i = N
if rem(i,3) == 0 || rem(i,5) == 0
v(i,1) = i
end
end
Te problem is that I get an Array with some zeros in, but I just want an an arraywith the values comforming to my conditions.
How can I fix it?
Thank you!
I think the OP is looking for a result like:
v= N( (rem(N,3)==0) | (rem(N,5)==0) );
though without looping... :-)
I'm assuming that you're using a loop for a reason, and am not removing it from my solution. However, loops should be avoided where possible.
If I understand your question, you're trying to store only those values of i which correspond to a true conditional evaluation. You're problem is that you're using i as your index value inside the assignment statement. Use the end index keyword. Like so:
N = 1:999;
v = [];
for i = N
if rem(i,3) == 0 || rem(i,5) == 0
v(end+1) = i
end
end

Copy text from a string that meets a certain condition MATLAB

i have a strings from a text file:
20130806_083642832,!AIVDM,1,1,,B,13aFeA0P00PEqQNNC4Um7Ow`2#O2,0*5E
20130806_083643032,!AIVDM,2,1,4,B,E>jN6<0W6#1WPab3bPa2#LtP0000:uoH?9Ur,0*50
i need to go through the characters and extract the date at the start then the message that starts after B, (but could also be A,) up until ,0
Any thoughts?
Ok, there are much more elegant ways to solve this, but my following example will give you a feeling on how to manipulate strings in MatLab (Which might be the thing you are having problems with). Here you go:
String='20130806_083642832,!AIVDM,1,1,,B,13aFeA0P00PEqQNNC4Um7Ow`2#O2,0*5E'
for i=1:length(String)
if(strcmp(String(i),'B')) %or strcmp(String(i),'A')
for j=i:length(String) %or "for j=length(String):i" if you meant the last 0 ;)
if(strcmp(String(j),'0'))
String2=String(i:j)
break
end
end
break
end
end
Output
String =
20130806_083642832,!AIVDM,1,1,,B,13aFeA0P00PEqQNNC4Um7Ow`2#O2,0*5E
String2 =
B,13aFeA0
Just play around with string indexing and with strcmp or strcmpi and you'll get a feeling and will be able to write much nicer expressions.
Now try extracting the date by yourself!
Hope that helps!
Without loops you could do something like this:
startString = ['20130806_083642832,!AIVDM,1,1,,B,13aFeA0P00PEqQNNC4Um7Ow`2#O2,0*5E'];
startPosition = find(startString == 'B') + 1;
if ~startPosition
startPosition = find(startString == 'A') + 1;
end
tmpMessage = startString(startPosition:end);
endPosition = find(tmpMessage == '0') - 1;
outMessage = tmpMessage(1:endPosition(1))
dateString = startString(1:8)
This gives the output:
outMessage = ,13aFeA
dateString = 20130806

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.