MATLAB console output - matlab

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));

Related

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!

Matlab ShortEng number format via sprintf() and fprintf()?

I like using MATLAB's shortEng notation in the interactive Command Window:
>> a = 123e-12;
>> disp(a);
1.2300e-10 % Scientific notation. Urgh!
>> format shortEng;
>> disp(a);
123.0000e-012 % Engineering notation! :-D
But I want to use fprintf:
>> format shortEng;
>> fprintf('%0.3e', a);
1.2300e-10 % Scientific. Urgh!
How do I print values with fprintf or sprintf with Engineering formatting using the MATLAB Format Operators?
I know I could write my own function to format the values into strings, but I'm looking for something already built into MATLAB.
NOTE: "Engineering" notation differs from "Scientific" in that the exponent is always a multiple of 3.
>> fprintf('%0.3e', a); % This is Scientific notation.
1.230000e-10
There is no way to use directly fprintf format specifier for the format you require. A way around is to use the output of disp as a string to be printed. But disp doesn't return a string, it writes directly to the standard output. So, how to do this?
Here's where evalc (eval with capture of output) comes to the rescue:
%// Create helper function
sdisp = #(x) strtrim(evalc(sprintf('disp(%g)', x)));
%// Test helper function
format ShortEng;
a = 123e-12;
fprintf(1, 'Test: %s', sdisp(a));
This is a workaround, of course, and can backfire in multiple ways because of the untested inputs of the helper functions. But it illustrates a point, and is one of the rare occasions where the reviled eval function family is actually irreplaceable.
You can use the following utility:
http://www.people.fas.harvard.edu/~arcrock/lib118/numutil/unpacknum.m
This will unpack the number also according to a given number N and makes sure that the exponent will be a multiple of N. By putting N=3 you have the Engineering Notation.
More into detail, unpacknum takes 3 arguments: the number x, the base (10 if you want Engineering Notation) and the value N (3 if you want Engineering Notation) and it returns the couple (f,e) which you can use in fprintf().
Check the unpacknum help for a quick example.
This function converts a value into a string in engineering notation:
function sNum = engn(value)
exp= floor(log10(abs(value)));
if ( (exp < 3) && (exp >=0) )
exp = 0; % Display without exponent
else
while (mod(exp, 3))
exp= exp - 1;
end
end
frac=value/(10^exp); % Adjust fraction to exponent
if (exp == 0)
sNum = sprintf('%+8.5G', frac);
else
sNum = sprintf('%+8.5GE%+.2d', frac, exp);
end
end
You can finetune the format to your liking. Usage in combination with fprintf is easy enough:
fprintf('%s\t%s\n', engn(543210.123), engn(-0.0000567)) % +543.21E+03 -56.7E-06
fprintf('%s\t%s\n', engn(-321.123), engn(876543210)) % -321.12 +876.54E+06
You can use the following utility posted to the MATLAB file exchange:
num2eng
It offers extensive control over the formatting of the output string and full input checking, so is more flexible and less prone to error than the simpler evalc approach suggested by user2271770.
It can also output strings using SI prefixes instead of engineering notation, if you prefer.

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

Using input dialog boxes in 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).