Matlab, Basics about Loops - matlab

I need to ask the user for a temperature, k or K stands for kelvin, c or C stands for celsius and f or F stands for Fahrenheit. How can I put all of those in a loop? I need to keep asking the user until they enter in one of the letters above. This is what I have so far.
tempType = input('What type of temperature would you like to use: ', 's');
value = ['k','K','c','C','f','F'];
while strcmp(tempType, value) == 1
tempType = input('What type of temperature would you like to use: ', 's');
end

I'd rather do like this to avoid two exactly same lines (tested in R2011b):
AllowedTemperature = {'k','K','c','C','f','F'};
SelectedTemperature = '';
while ~any(strcmp(SelectedTemperature,AllowedTemperature))
SelectedTemperature = input('What type of temperature would you like to use: ', 's');
end
disp( [ 'SelectedTemperature: ' SelectedTemperature ] )

You want (length(tempType)~=1 || length(findstr(tempType,value))==0) to be the condition of your while

Related

how write the following matlab code if want to fill data by for loop?

the given matlab code want to write by using "for loop"
how I can do that ?
g = {'P1','P1','P2','P2','P3','P3','P4','P4'};
I want this data by using for loop:
for f_no=1:8
g{f_no}=p(count);
count=count+1;
end
consider p has all dataset, how do I fill this as dynamic way into cell 'g'?
which will work as :
g = {'P1','P1','P2','P2','P3','P3','P4','P4'};
There are probably dozens of ways to do what you are asking. Here are 2.
%Loop
g = cell(8,1);
for p=1:4
g{p*2-1} = num2str(p,'P%d');
g{p*2} = num2str(p,'P%d');
end
%No Loop
g = cellstr(num2str(sort([1:4 1:4].'),'P%d'));
count = 1;
for f_no=1:8
g{f_no}=['P' num2str(count)];
count=count+1;
end
gives you
g = { 'P1' 'P2' 'P3' 'P4' 'P5' 'P6' 'P7' 'P8' }
OTOH,
count = 1;
for f_no=1:8
g{f_no}=['P' num2str(floor(count))];
count=count+.5;
end
gives you
g = { 'P1' 'P1' 'P2' 'P2' 'P3' 'P3' 'P4' 'P4' }
My solution:
N = [1 2 3 4];
P = repelem(N,2);
result = arrayfun(#(x)sprintf('P%d',x),P,'UniformOutput',false);
It makes use of the repelem function for duplicating each number in the vector N and of the arrayfun function for converting each number into a properly formatted string.
Alternatively, you can also use the undocumented function sprintfc and change the last line as follows:
result = sprintfc('P%d',P)
Always try to vectorize your code as much as possible when using Matlab, it performs sooooooo much better!
for f_no=1:4
g{2*f_no-1}=['P' num2str(f_no)];
g{2*f_no}=['P' num2str(f_no)];
end
It looks like 'P1' denotes p(1) cell value in which case the answer will be the same
n=size(p);
for f_no=1:n
g{2*f_no-1}=p(f_no);
g{2*f_no}=p(f_no);
end

Error using == Matrix dimensions must agree

my system will give me the a/m error when I input more than 3 characters
a = input('Please type f0 or f1: ' , 's');
if a == 'f0';
Run_f0
elseif a == 'f1';
Run_f1
else
disp('Please enter f0 or f1 only');
end
what should I do to resolve this error?
Thanks in advance
Matlab will compare each character of both strings. If one string is longer than the other one, there is nothing to compare and it will throw an error. You can bypass this by forcing the user to repeat the input until he gives a valid input:
valid = {'f0', 'f1'}
a = input('Please type f0 or f1: ' , 's');
while not(ismember(a, valid)) %// or: while not(any(strcmp(a, valid)))
a = input('Please really type f0 or f1: ' , 's');
end
The user will be asked to really input 'f0' or 'f1'.
As an alternative, you can consider to compare the strings with strcmp():
if strcmp(a, 'f0')
%// something
elseif strmpc(a, 'f1')
%// something else
else
disp('Please enter f0 or f1 only');
end
To compare strings you should use the function strcmp
a='12345'
strcmp('f01',a)
Returns: 0 (False)
a='f01'
strcmp('f01',a)
Returns: 1 (True)

Matlab function return value

I have one program that has function and the problem, return value, it has too many output.
Like exempley: y = text the answer comes up
Error in text (line 2)
if nargin == 0
Output argument "array" (and maybe others) not assigned during call to "
C:\Users\name\Documents\MATLAB\text.m>text".
The program text.m reads a txt file that contains a couple of names and numbers like
exemple:
John doughlas 15986
Filip duch 357852
and so on. The program convert them to 15986 Doughlas John and so on.
function array = text(~)
if nargin == 0
dirr = '.';
end
answer = dir(dirr);
k=1;
while k <= length(answer)
if answer(k).isdir
answer(k)=[];
else
filename{k}=answer(k).name;
k=k+1;
end
end
chose=menu( 'choose file',filename);
namn = char(filename(chose));
fid = fopen(namn, 'r');
R = textscan(fid,'%s %s %s');
x=-1;
k=0;
while x <= 24
x = k + 1;
All = [R{3}{x},' ',R{1}{x},' ',R{2}{x}];
disp(All)
k = k + 1;
end
fclose(fid);
Is there anyway to fix the problem without starting over from scratch?
Grateful for all the answers!
You specify the function output argument in the definition, but you don't assign anything to it in the function body.
For example, in
function y = student(j)
your output is y. So you have to assign something to y.
Read more about functions in MATLAB.
Here is a working example.
The first part is to create a function called 'functionA' in a filename 'functionA.m'. Then put the following code inside:
function result = functionA(N,alpha)
result = 5;
return
end
The second part is to create another Matlab file(i.e. upto you to name it) or you can use the Matlab command window even. Then run the following code:
getresult = functionA(100,10);
getresult
After running you get the following answer:
ans =
5

How to repeat an input if the user didn't type in anything and edit the entered input in matlab?

For example I have
x = input('value = ?')
how can I repeat this command if the user just press enter without any input and I would like to know is there anyway I could edit my input like just pressing the 'backspace' after I have keyed in.
Like I got two input variable now'
x = input('??');
y = input('???');
can I edit my first input if I have insert the first input data for x when the input function y is prompted out.
sincerely thanks for anyone that willing to give some helps.
For the 1st case:
I would like to have a code something like this
x = input('value = ?');
while x == %%no input%%
x = input('value = ?'); %prompt the input command again
end
and
while x==error %% I want x in numeric input only
x = input('value = ?'); %prompt the input command again
end
For the first case:
x = input('??'); % if the user just hits 'enter' x is an empty variable
while isempty( x )
x = input('??');
end
For a more robust method
x = str2double( input('Your input here:', 's') );
while ~isnan( x )
x = str2double( input('Your input here:', 's') );
end
the command input('??', 's') returns the input "as-is" and does not try to convert it to a number. The conversion is done via the command str2double. Now, if the input is not a number (double), then str2double returns NaN. This can be captured by isnan.
Hopes this works for you.
to repeat for blanks,
x=''
while isempty(x)
x=input('value=');
end
for non-numeric, you could use something like
x=''
while isempty(x)
try
x=input('value=')
catch me
fprintf('enter a number\n')
end
end

Function, in MATLAB dna replication

I'm trying to figure out the function command in Matlab and im having some difficulties.
I'm trying to write a Matlab function named dna_replicate. It will replicate a given strand and return its partner strand
For example if the user enters ATGCATGCAHGCAGTC, it should return TACGTACGT CGTCAG
A-->T
G-->C if the user enters other than these 4 letters, there should be blank in the partner strand. Thank you for your help
This implementation should be faster, involving only a simple table look-up. Note that the table t is constructed only once when the function is first called.
function out = dna_replicate(in)
persistent t
if isempty(t)
t = blanks(256);
t('ATGC') = 'TACG';
end
out = t(in);
end
How about:
function out = dna_replicate(in)
in = upper(in); % Ensures all same case
A = in=='A';
T = in=='T';
C = in=='C';
G = in=='G';
out = in;
out(A) = 'T';
out(T) = 'A';
out(C) = 'G';
out(G) = 'C';
out(~(A|T|C|G)) = ' ';
while #Jirka cigler answer works, it uses a for loop as well as dynamically growing vector 'out'. As matlab is optimized for vector operations, this answer should perform better.
You can create a simple vectorized solution using the function ISMEMBER:
function outString = dna_replicate(inString)
[~,index] = ismember(upper(inString),'ACGT'); %# Find the indices of inStrings
%# letters in string `ACGT`
outString = 'ACGT '; %# Initialize outString to `ACGT` and a blank
outString = outString(5-index); %# Use inverted and shifted index to expand
%# outString to the size of inString
end
And here's a test:
>> dna_replicate('ATGCATGCAHGCAGTC')
ans =
TACGTACGT CGTCAG
I think it can be implemented as follows:
function out=dna_replicate(in)
for i=1:numel(in)
switch in(i)
case 'A'
out(i)= 'T';
case 'G'
out(i)= 'C';
case 'T'
out(i)='A';
case 'C'
out(i)='G';
otherwise
out(i)=' ';
end
end
this function has argument of type char
in='ATGCATGCAHGCAGTC'
and you can run
out=dna_replicate(in)
to get the same result as you want :-)