Asking a Yes or No query in MATLAB

2019-04-16 11:48发布

问题:

I have written a script in MATLAB, where I am retrieving rows and columns from a table based on the WHERE clause. So far i manage to retrieve the data from the database table.

The problem is that i would like to allow the user to have the option of running another search to retrieve another set of data.

This is my code so far that i have and the script is called 'searchpdb'.

pdbSearch = input('Enter your PDB Code: ', 's')
curs = fetch(exec(conn, ['SELECT * FROM cath_2_wo_dup WHERE pdbcode = ' '''' pdbSearch '''']));
fprintf('Results Successful! \n');
results = curs.Data % prints the data out

% ----------------------
% User option to search again
% -----------------------

goAgain = input('Would you like to search for another pdb?', 's');
% if (goAgain = 'Yes')
if strcmp(goAgain, 'Yes')
    searchpdb(); %runs this script again.
elseif strcmp(goAgain, 'No')
    fprintf('\nBye!\n');

end

I have tried using 'questdlg', but it does not show the results of the data in the table after i have given the option to the user to run again.

I am doing this the wrong way, or is there another efficient way of doing it? Should the option of running the script again be in another script ?

回答1:

Well, it will work, but I would recommend using a while clause instead of calling the script recursively:

goAgain = true;
while goAgain
    pdbSearch = input('Enter your PDB Code: ', 's');
    curs = fetch(exec(conn, ['SELECT * FROM cath_2_wo_dup WHERE pdbcode = ' '''' pdbSearch '''']));
    fprintf('Results Successful! \n');
    results = curs.Data % prints the data out

    % ----------------------
    % User option to search again
    % -----------------------

    res = input('Would you like to search for another pdb?', 's');
    goAgain = isequal(upper(res),'YES');
end

It just becomes clearer for the reader of your code. Just by taking a look at the first lines of this new code, one can guess that:

  1. There is a loop - something happens multiple times.
  2. There is a stop condition called goAgain.


回答2:

What is the problem, exactly? The following test script (called scriptrecurse.m) works as expected (note that you don't need the parentheses () to call a script).

X = randn(3);
disp('X = ')
disp(X)

x = input('Go again? ','s');

if strcmpi(x,'y')
    scriptrecurse
else
    fprintf('Bye!\n')
end

For example:

>> scriptrecurse
X = 
    1.1808    0.4716   -1.4529
    0.1729    2.0474   -0.6343
    0.1747   -0.6437   -1.1136

Go again? y
X = 
   -0.8910   -0.2479    0.0851
    1.7106    2.0659    0.6639
   -0.5174   -0.4350    0.0301

Go again? n
Bye!