Using input dialog boxes in Matlab - matlab

Suppose I have a function that is something like this:
function [ c ] = input_args(m)
for i = 1 : m+1
c{i} = inputdlg('Enter next m value');
end
end
Now I'd like to change this so that the instruction to the user at the i'th stage of the for loop says something like "Enter the i'th m value", where i is the changing index in the for loop. How can I do this?
Thanks!

A string is a array of characters, so you can concatenate them like any other array. You need to use num2str to convert a number into a printable character.
inputdlg(['Enter the ' num2str(i) 'th m value']);
A more general solution would be to use sprintf to format your string; to do the same thing with sprintf you would use:
inputdlg(sprintf('Enter the %dth m value', i));
which you might find more readable (and allows you to use standard fprintf formatting options).

Related

How to print a chain of arrows with fprintf

I am looking for a way to set up the fprintf function so that it returns the string 1->2->...->n for any input n. However, I cannot find a way to do so without having an extra arrow attached at the beginning (->1->2->...->n) or the end of the string (1->2->...->n->). Is there a way around this?
You could use strjoin for this...
n = 4;
str = strjoin( arrayfun(#num2str, 1:n, 'uni', 0), '->' );
% str = '1->2->3->4'
Or if you're set on using fprintf (or sprintf), you could manually add the first element (for ease, assume n >= 1)
str = ['1', sprintf('->%.0f', 2:n )];
If you just want to print these to the Command Window, simply use disp on either option instead of (or after) assigning to str. If you're writing to a file with fprintf then simply use fprintf( fid, [str '\n'] ) to print the line to file.
For this type of task, the solution is to print either the first or the last element separately:
n = 8;
fprintf('%d', 1);
fprintf('->%d', 2:n);
fprintf('\n');
Here's another approach to build the desired string:
n = 10;
str = regexprep(num2str(1:n), '\s+', '->');
This gives
str =
'1->2->3->4->5->6->7->8->9->10'

Is it possible to surpress that "input" jumps to the next line?

I got a code similar to this:
fprintf('Give a vector: \n')
fprintf('1. Vector/Matrix: X = {')
FirstVector = input('','s');
fprintf('}')
fprintf('\n')
It should print out something like this:
Give a vector:
1. Vector/Matrix: X = {UserInput}
Instead I get this:
Give a vector:
1. Vector/Matrix: X = {UserInput
}
The input-function is making a \n. How can I avoid that? The documentation of input is of no use, it doesn't even tell that input behaves that way.
You can get around this inherent limitation of input by adding a backspace character to the fprintf after the input. You can also condense your code into two lines, like so:
FirstVector = input('Give a vector: \n1. Vector/Matrix: X = {', 's');
fprintf([char(8) '}\n']);
Entering a 1:
Give a vector:
1. Vector/Matrix: X = {1}
Note also that the 's' option is for capturing character/string input. If you want the user to enter numeric values, leave that out.

Creating a function with variable number of inputs?

I am trying to define the following function in MATLAB:
file = #(var1,var2,var3,var4) ['var1=' num2str(var1) 'var2=' num2str(var2) 'var3=' num2str(var3) 'var4=' num2str(var4)'];
However, I want the function to expand as I add more parameters; if I wanted to add the variable vark, I want the function to be:
file = #(var1,var2,var3,var4,vark) ['var1=' num2str(var1) 'var2=' num2str(var2) 'var3=' num2str(var3) 'var4=' num2str(var4) 'vark=' num2str(vark)'];
Is there a systematic way to do this?
Use fprintf with varargin for this:
f = #(varargin) fprintf('var%i= %i\n', [(1:numel(varargin));[varargin{:}]])
f(5,6,7,88)
var1= 5
var2= 6
var3= 7
var4= 88
The format I've used is: 'var%i= %i\n'. This means it will first write var then %i says it should input an integer. Thereafter it should write = followed by a new number: %i and a newline \n.
It will choose the integer in odd positions for var%i and integers in the even positions for the actual number. Since the linear index in MATLAB goes column for column we place the vector [1 2 3 4 5 ...] on top, and the content of the variable in the second row.
By the way: If you actually want it on the format you specified in the question, skip the \n:
f = #(varargin) fprintf('var%i= %i', [(1:numel(varargin));[varargin{:}]])
f(6,12,3,15,5553)
var1= 6var2= 12var3= 3var4= 15var5= 5553
Also, you can change the second %i to floats (%f), doubles (%d) etc.
If you want to use actual variable names var1, var2, var3, ... in your input then I can only say one thing: Don't! It's a horrible idea. Use cells, structs, or anything else than numbered variable names.
Just to be crytsal clear: Don't use the output from this in MATLAB in combination with eval! eval is evil. The Mathworks actually warns you about this in the official documentation!
How about calling the function as many times as the number of parameters? I wrote this considering the specific form of the character string returned by your function where k is assumed to be the index of the 'kth' variable to be entered. Array var can be the list of your numeric parameters.
file=#(var,i)[strcat('var',num2str(i),'=') num2str(var) ];
var=[2,3,4,5];
str='';
for i=1:length(var);
str=strcat(str,file(var(i),i));
end
If you want a function to accept a flexible number of input arguments, you need varargin.
In case you want the final string to be composed of the names of your variables as in your workspace, I found no way, since you need varargin and then it looks impossible. But if you are fine with having var1, var2 in your string, you can define this function and then use it:
function str = strgen(varargin)
str = '';
for ii = 1:numel(varargin);
str = sprintf('%s var%d = %s', str, ii, num2str(varargin{ii}));
end
str = str(2:end); % to remove the initial blank space
It is also compatible with strings. Testing it:
% A = pi;
% B = 'Hello!';
strgen(A, B)
ans =
var1 = 3.1416 var2 = Hello!

Create a matrix from all the variable in the workspace starting with a specified name

For example, imagine that I've in my workspace 100 variables whoes names range from var_1 to var_100. Now I want to create a matrix using all the variable starting with the name 'var_'.
I know I could try to list all the variables, but that would be ineficient and long:
A = [var_1 var_2 ... var_100]
Is there a better way to do complish this?
While this is probably (most definitely) not a good idea, here is what you can do:
varstr = 'A = ['
for ii = 1:100
varstr = [varstr, ' var_', num2str(ii)];
end
varstr = [varstr, '];']
eval(varstr)
The eval function lets you execute a string of matlab code. Therefore, you just need to generate a string that constructs the array, then pass it to eval. Fortunately, this is pretty easy:
eval([ 'A = [' sprintf('var_%d, ', 1:100) ']']);
It might be a little clearer if you actually do the assignment outside of the eval, like so
A = eval([ '[' sprintf('var_%d, ', 1:100) ']']);
Note that the string here has an extra trailing comma. That doesn't seem to be a problem, at least on 2014b.
If you don't know the total number of variables, you can get them with the who command. This returns a cell array of strings, which you'd then reformat and pass to eval, like so
my_variables = who('var_*');
% You may want to sort (re-order, take a subset of) my_variables here
str_to_run = '['
for ii=1:length(my_variables)
str_to_run = [str_to_run, my_variables{ii}, ',']
end

MATLAB console output

Say I had a variable called "x" and x=5.
I would like to do:
disp('x is equal to ' + x +'.');
and have that code print:
x is equal to 5.
This is how I am used to doing things in Java, so their must be a similar way to do this in MATLAB.
Thanks
If you want to use disp, you can construct the string to display like so:
disp(['x is equal to ',num2str(x),'.'])
I personally prefer to use fprintf, which would use the following syntax (and gives me some control over formatting of the value of x)
fprintf('x is equal to %6.2f.\n',x);
You can, of course, also supply x as string, and get the same output as disp (give or take a few line breaks).
fprintf('x is equal to %s\n',num2str(x))
printing out a few scalar variables in matlab is a mess (see answer above). having a function like this in your search path helps:
function echo(varargin)
str = '';
for k=1:length(varargin)
str = [str ' ' num2str(varargin{k})];
end
disp(str)
just nest a sprintf() inside the disp().
disp(sprintf("X is equal to %d.",x));