What is the meaning of ~ apart from logical not? - matlab

What does following code do in Matlab? I searched documentation but ~ shows logical not. But I could not relate following output to anything about logical not.
[~, k ] = max([0.9 1.5 4.6; 3.31 0.76 5.4]
Output: 2 1 2

The ~ placeholder allows you to ignore an output from a function. Using this allows you to acknowledge that something is output by the function, but you do not have to allocate a variable to store the output in.
When a function returns values in Matlab the number of parameters it returns and the order of these parameters is important and allows you to know what each returned value is. You may sometimes come across situations where a function returns more values than you are interested in, and you can ignore the ones you are not interested in using ~.
In your example, M = max([0.9 1.5 4.6]) would return only the maximum value. If you want to know the index of the maximum value, you have to use [M,I] = max([[0.9 1.5 4.6]). If you need to know the index of the maximum value but are not interested in the actual value itself, you can use [~,I] = max([0.9 1.5 4.6]), and you thus do not need to allocate a variable to hold the maximum values.

The according reference you're looking for is the Symbol Reference, which states:
Tilde — ~
The tilde character is used in comparing arrays for unequal values,
finding the logical NOT of an array, and as a placeholder for an input
or output argument you want to omit from a function call. Not Equal to
...
Argument Placeholder
To have the fileparts function return its third output value and skip
the first two, replace arguments one and two with a tilde character:
[~, ~, filenameExt] = fileparts(fileSpec);
which is what #David suggested in his comment.

Related

MatLab: Error checking for integers in a row vector

I have used MatLab to write the following code for Horner's Algorithm
function [answer ] = Simple( a,x )
%Simple takes two arguments that are in order and returns the value of the
%polynomial p(x). Simple is called by typing Simple(a,x)
% a is a row vector
%x is the associated scalar value
n=length(a);
result=a(n);
for j=n-1:-1:1 %for loop working backwards through the vector a
result=x*result+a(j);
end
answer=result;
end
I now need to add an error check to ensure the caller uses integer values in the row vector a.
For previous integer checks I have used
if(n~=floor(n))
error(...
But this was for a single value, I am unsure how to do this check for each of the elements in a.
You've got (at least) two options.
1) Use any:
if (any(n ~= floor(n)))
error('Bummer. At least one wasn''t an integer.')
end
Or even more succinctly...
assert(all(n == floor(n)), 'Bummer. At least one wasn''t an integer.')
2) Use the much more capable validateattributes:
validateattributes(n, {'double'}, {'integer'})
This function can check for more than a dozen other things, too.
Same math will work, but is now checking each element. Try this:
if any(n~=floor(n))
error(...

What does this symbol ~ do in matlab

I am student in physics and they gave me a program in matlab to get some results. Is some point matlab crashes and indicates the problem at this line:
[~,idx] = min(cf(:));
error message is:
Expression or statement is incorrect--possibly unbalanced (, {, or [.
I want to ask what does ~ do in matlab? At my search in google I found that ~ is the approximately symbol. So what reason does it have to be there?
The tilde in that expression is used to ignore the first return value from the min function. That syntax has only been around for a few years, it's possible the error is occurring because you're using an older version of MATLAB.
Try replacing the ~ with idx. That'll cause the second return value to overwrite the first one, and will be functionally equivalent to the code you've posted.
In other contexts, ~ is the logical not operator and ~= is a logical comparison operator for testing inequality.
min function can return two values, where the first is the minimum value of the input array and the second is the index corresponding to the minimum value. Sometimes you don't really need the actual minimum value, so for the first return value you just put ~ there as a place holder, without assigning it to a specific variable.
The error is probably associated with an unbalanced statement in preceding lines of the function call you are showing

Capture all possible outputs based on variable number of inputs.

I would like Matlab to return all the outputs from a variable input function. For instance,
[varargout]=cpd_intersect(varargin{:});
This only returns the last output but I know the function is defined to give multiple outputs.
Instead of defining dummy variables A, B , C etc in [A,B,C...]=pd_intersect(varargin{:}). I would like something like a cell to store all the output values based on the input number of values. I hope this makes sense. Many thanks in advance.
I know this is late, but I think this is what you want:
function [varargout] = myfun(f, varargin)
% apply f to args, and return all its outputs
[ x{1:nargout(f)} ] = f(varargin{:}); % capture all outputs into a cell array
varargout = x; % x{:} now contains the outputs of f
The insight here is that
NARGOUT can operate on functions and returns their maximum number of outputs
using [ X{1:2} ] = ...on the left hand side when X is undefined, is equivalent to doing [ X{1} X{2} ] = ..., and can capture 2 separate outputs into individual variables.
Two points to note:
this works for anonymous functions too! e.g. #(x)eig(x)
it won't work for functions that use varargout, i.e. functions with truly variable numbers of outputs. If this is the case then there should be a way to calculate how many outputs you are going to have, e.g. using nargin.
PS I learnt this from #gnovice, If a MATLAB function returns a variable number of values, how can I get all of them as a cell array?
You can do this by returning a cell array
I see you cannot force a variable comma separated output list in Matlab. Pity. It would be useful. It seems I have to explicitly assign each output. This sucks since I do not know beforehand the number of outputs I will get.

What is the meaning of this command

capi = cell2mat(arrayfun(#(b) sum(resulti == b,1),nonzeros(unique(resulti)), 'UniformOutput', false))
why when I used that code, my code cannot run and there was command like the following command?
??? Array dimensions must match for binary array op.
All this can be found via Matlab's documentation, which should always be your first step!
Having said that, here's a breakdown of your command:
cell2mat: convert a cell array to a matrix according to some format you define
arrayfun: evaluate some function for all elements in an array. The function may be an anonymous function (e.g., #(b) sum(resulti == b,1))
sum: sum all the elements of a matrix in a particular direction. Direction 1: down the rows, direction 2: along the columns, etc.
nonzeros: form new array by removing all zeros from the input array. This will output a column vector, irrespective of the input's shape.
unique: return the input array with all duplicates of all values removed. The output will also be sorted.
Type help [command] or doc [command] for more information on all these commands (which I recommend you do!)
Now, combining these into your command:
A = nonzeros(unique(resulti))
will return all unique entries in a column vector, with any zero removed.
B = arrayfun(#(b)sum(resulti==b), A, 'UniformOutput', false)
will run the function #(b) sum(resulti == b,1) on all entries of the newly created column vector A, and collect them in a cell-array B (cell, because 'UniformOutput' is set to false). This function will simply compare each element of resulti against the running index b, and find the total count along the rows. Then, finally,
capi = cell2mat(B)
will convert the cell-array B back to a normal Matlab array.
The objective of this command seems to be to count the number of non-unique occurrences on each of the colums of resulti. As hinted at by #GuntherStruyf, this whole command seems a hacked-together, forced one-liner, rather than well-manageable, readable code. I would personally opt to break it over several lines, avoid arrayfun (slow) and instead use bsxfun or a for-loop (faster (yes, also the for-loop), better readable).
But that's a matter of opinion (which goes against popular opinion :)

Concatenate equivalent in MATLAB for a single value

I am trying to use MATLAB in order to generate a variable whose elements are either 0 or 1. I want to define this variable using some kind of concatenation (equivalent of Java string append) so that I can add as many 0's and 1's according to some upper limit.
I can only think of using a for loop to append values to an existing variable. Something like
variable=1;
for i=1:N
if ( i%2==0)
variable = variable.append('0')
else
variable = variable.append('1')
i=i+1;
end
Is there a better way to do this?
In MATLAB, you can almost always avoid a loop by treating arrays in a vectorized way.
The result of pseudo-code you provided can be obtained in a single line as:
variable = mod((1:N),2);
The above line generates a row vector [1,2,...,N] (with the code (1:N), use (1:N)' if you need a column vector) and the mod function (as most MATLAB functions) is applied to each element when it receives an array.
That's not valid Matlab code:
The % indicates the start of a comment, hence introducing a syntax error.
There is no append method (at least not for arrays).
Theres no need to increment the index in a for loop.
Aside of that it's a bad idea to have Matlab "grow" variables, as memory needs to be reallocated at each time, slowing it down considerably. The correct approach is:
variable=zeros(N,1);
for i=1:N
variable(i)=mod(i,2);
end
If you really do want to grow variables (some times it is inevitable) you can use this:
variable=[variable;1];
Use ; for appending rows, use , for appending columns (does the same as vertcat and horzcat). Use cat if you have more than 2 dimensions in your array.