Need help on clarification of input dialog of matlab - matlab

Suppose I have the following code:
%%input dialog box%%%
prompt = {'Enter gain:','Enter range:'};
dlg_title = 'Enter values';
num_lines= 1;
def = {'20','256'}; %default
answer = inputdlg(prompt,dlg_title,num_lines,def);
%%%to get the two entered values%%%%
A = getfield(answer,{1}); %first input field
A = str2double(A);
B = getfield(answer,{2}); %second input field
B = str2double(B);
What does it mean to use "dynamic field names with structures instead of getfield"?
How can I use a loop for the input values that are complex and smaller than zero, in the sense to request the user for another compatible input?
I've tried the following loop but it does not work. Why?
while isnan(A) || ~isreal(A) || A<0
prompt = {'Enter gain:'%'Enter range:'};
dlg_title = {'undefine!!'};
num_lines= 1;
def = {'',''}%{'20','256'}; %default
answer = inputdlg(prompt, dlg_title, num_lines, def);
A = getfield(answer,{1}); %first input field
A = str2double(A);
%A = str2double(input('Enter the value of module(mm) : ', 's'));
end

The calls to getfield aren't required and frankly don't make any sense. The variable answer is a cell array not a struct so you don't need to use getfield The second half of the pasted code could be replaced with:
A = str2double( answer{1} );
B = str2dobule( answer{2} );
With regards to looping until you get valid input. You can use a boolean flag, a while, loop and a function (lets call it areInputsValid()) that returns true if the inputs are valid
validInput = false;
while (~validInput)
% input dialog box
% code here
% get the two entered values
& code here
validInput = areInputsValid(A, B);
end

Related

How to adjust the size of block.outputport.data in Matlab?

I have tried to generate a square pulsed clock. But it gives error. I tried this:
function pll( block)
setup(block);
function setup(block)
% Register number of ports
block.NumInputPorts = 1;
block.NumOutputPorts = 1;
% Override input port properties
block.InputPort(1).Dimensions = 1;
block.InputPort(1).DatatypeID = 8; % boolean
block.InputPort(1).Complexity = 'Real';
block.InputPort(1).DirectFeedthrough = false;
% Override output port properties
block.OutputPort(1).Dimensions = 1;
block.OutputPort(1).DatatypeID = 0; %double
block.OutputPort(1).Complexity = 'Real';
block.NumDialogPrms = 1;
block.DialogPrmsTunable = 0;
ts = 1/24000000'; %'
block.sample times= [ts 0];
block.SimStateCompliance = 'DefaultSimState'
function Outputs(block)
t = [0:1/(24000000):0.000001];
l = 0.1*exp(-6);
c = 220*exp(-9) + 60*exp(-9);
f = 1/(2*pi*sqrt(l*c));
block.OutputPort(1).Data = square(2*pi*f*t);
function Terminate(block)
But it gives me the error
"Error evaluating registered method 'Outputs' of M-S-Function 'pll' in
'untitled/Level-2 M-file S-Function'. Invalid assignment in
'untitled/Level-2 M-file S-Function': attempt to assign a vector of
width 24001 to a vector of width 1."
the error indicates on the line
block.OutputPort(1).Data = square(2*pi*f*t);
so what can be done to overcome this error?
It seems from your example that you're not really familiar with the way Simulink works. At each time step, each block in a Simulink model outputs a value (i.e the block's output value) corresponding to the current simulation time. In your case, within the block.Output function you are trying to output all time points at every simulation time step.
It appears that what you really want is to replace
t = [0:1/(24000000):0.000001];
with
t = block.CurrentTime;
And replace
block.OutputPort(1).Data = square(2*pi*f*t);
with
block.OutputPort(1).Data = sign(sin(2*pi*f*t));
Also, some other things to consider:
you don't seem to be registering the block's output method using:
block.RegBlockMethod('Outputs',#Output);
Why have you defined the block to have an input when it doesn't seem to require one?
Why are you doing this in an S-Function when a From Workspace block (or one of the many other ways to get data into a model) would seem to make more sense?

Numeric Data Validation While Loop in Matlab

I have a function usenum
function TF = usenum(x)
TF = false;
if ~isnumeric(x)
h = msgbox('Input is not numeric');
elseif (x <= 0)
h = msgbox('Input must be > 0');
else
TF = true;
end
I am getting user input in the main menu:
answer = inputdlg(prompt,dlg_title,num_lines,def);
The inputdlg has 2 values and can be indexed by {1} and {2}
I want to wait for the user to input a value, the value has to be a number and greater than 0. in the case that he doesn't, I want to output the respective message and make him keep inputting until he gets it right, or close the inputdlg dialog.
I am attempting something like this:
condition = false;
while ~condition
answer = inputdlg(prompt,dlg_title,num_lines,def);
numOfTracks = answer{1};
bpmRange = answer{2};
condition = usenum(numOfTracks);
end
I am trying to say, while condition = false, i.e. while input is not numeric or not greater than 0, keep getting user input. Once the user inputs a valid number the condition is supposed to become true and the while is supposed to terminate. However, the inputdlg keeps opening for input and the only way I can stop it is by closing it (infinite loop). how can I achieve what I want?
Thanks in advance
Your loop appears to be correct. The following testing provides results of your usenum function.
>> usenum('')
ans =
0
>> usenum(-1)
ans =
0
>> usenum(1)
ans =
1
Your usenum function is correct as far as typing is concerned, but I believe your input is always given as a string since you're getting user input from a dialogue. Instead, you should try redefine usenum as follows if you're expecting a string input. The function str2double converts it to a double and if it's text, it will show as NaN. That's what the isnan check is for, to check if it's text.
function TF = usenum(x)
% Default to false
TF = false;
x = str2double(x);
% Check if digits
if isnan( x )
h = msgbox('Input is not numeric');
elseif (x <= 0)
h = msgbox('Input must be > 0');
else
TF = true;
end
This is the result of the new function.
>> usenum('a')
ans =
0
>> usenum('-1')
ans =
0
>> usenum('1')
ans =
1

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 prevent input dialog box be closed in matlab?

how can the input dialog box can be avoided from directly close by the user without enter any value? for the 'menu' function we can form loop using while options==0 for unselected options but how about input dialog?
prompt = {'Enter gain:','Enter range:'};
dlg_title = 'Enter values';
num_lines= 1;
def = {'20','256'}; %default
answer = inputdlg(prompt,dlg_title,num_lines,def);
%%%to get the two entered values%%%%
%A = getfield(answer,{1}); %first input field
A = str2double(answer{1});
%B = getfield(answer,{2}); %second input field
B = str2double(answer{2});
suppose I have a input dialog as shown, how I can model it with the loop in complete way
You cannot prevent it from being closed, but you can use a while-loop to re-open it until the user has entered a useful value.
done = false;
while ~done
a=inputdlg('enter a number')
num = str2double(a{1}); %# will turn empty and strings into NaN
if isnumeric(num)
done = true;
else
%# keep running while loop
%# you can pop up an errordlg box here to tell the user what was wrong.
%# It would be nice if you were to set the inputs that passed the test
%# as defaults for the next call of inputdlg. Nothing sucks as much
%# as having to completely re-fill a form because of a small typo
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 :-)