I have a Matlab function which returns an array with probability alpha and nothing (i.e. an empty array) with probability 1-alpha:
function [binary_array_e1 , binary_array_e2 ] = croiser(binary_array_p1,binary_array_p2,alpha )
binary_array_e1=[];
binary_array_e2=[];
compt=1;
if (rand <= alpha)
% some stuff that will put sth in binary_array_e1 and binary_array_e2
end
My question is: how should I manage the fact that the function could return empty arrays at the call of the function? Is something like:
[binary_array_e1 , binary_array_e2]=croiser(binary_array_p1,binary_array_p2,alpha);
be sufficient?
If you want to return an empty variable from a function call, you are totally allowed to do it and you are on the right path. Initialize your variables as empty at the beginning of the function...
function [binary_array_e1 , binary_array_e2 ] = croiser(binary_array_p1,binary_array_p2,alpha )
binary_array_e1=[];
binary_array_e2=[];
% ...
end
and then just check the outcome whenever you need to do it, for example:
[binary_array_e1,binary_array_e2] = croiser(binary_array_p1,binary_array_p2,alpha);
if (isempty(binary_array_e1))
% do something 1...
elseif (isempty(binary_array_e2))
% do something 2...
else
% do something 3...
end
Of course, in order to check the outcome, both variables must be returned and evaluated. But if you are returning two empty arrays in one case and two non-empty arrays in the other case, you could also check only one array:
if (isempty(binary_array_e1))
% do something...
else
% do something else...
end
Anyway... there are so many ways to obtain the same result. For example, you could also return a 'logical' variable that tells you immediately if your arrays have been filled with something or not, or you could return a 'struct' filled with your data in order to make everything more compact (I can elaborate on these solutions if you want). It's up to you but I see nothing wrong in your approach!
Yes, that should be fine. You can later check if the output is an empty array using the function isempty
Related
I've been stuck with this for a while and I couldn't find something similar asked previously (or I have failed in doing so)
My situation is fairly simple: I have a cell array of objects. They are all the same object and I have a get function for this kind of object which is: get (obj, attr), where obj is the object in question and attr is a integer from 1-6. Depending on the number the get function returns the corresponding attribute.
I would like to obtain all of my "position" attributes from all my objects which are in the corresponding cell array (this would be attr = 2). I know that cellfun performs a function on all cells, but the question is, how do I use my get function here for all my objects, taking into account that the function is get (obj, attr) ?
Thanks in advance
Firstly, by using get as a custom function you are shadowing the built-in get function - this is bad practise!
With this in mind, and to avoid confusion with the built-in get function which has similar syntax, I'm going to use getattr as a stand-in for your custom function which accpets an object and an integer 1 to 6.
pos = cellfun( #(obj) getattr( obj, 2 ), myCellOfObjects, 'uni', 0 );
By specifying 'uni', 0, the output doesn't have to be scalar and will be put into a cell array. This is useful when, for example, you have a multi-element array for your position.
This is equivalent to the following loop:
pos = cell( numel(myCellOfObjects), 1 );
for ii = 1:numel(pos)
pos{ii} = getattr( myCellOfObjects{ii}, 2 );
end
If ever in doubt about cellfun or arrayfun, just write a loop first - they are essentially the same but more concise.
There is a trick to this some are unaware of: you can pass multiple arguments to cellfun like this:
cellfun(#(obj,attr) get(obj,attr), {obj1,obj2},{attr1,attr2},'uni',0)
if you want to get one attribute of the cellarray (instead of providing an attribute for every object in the cellarray), then you can simply use this
cellfun(#(x) getattr(x,attr),obj,'uni',0)
put into anonymous function for convenience:
get_attr = #(obj,attr) cellfun(#(x) getattr(x,attr),obj,'uni',0)
%use:
get_attr(obj_in_cellarray,'myattribute')
%returns cell array of object attributes
I haven't run any of these functions since you didn't provide any example data / code. Please test and feedback.
function [ muln, varargout ] = my_mul( varargin )
%MY_MUL This function is used to multiply numbers.
% My_mul function multiplies array of entered numbers, and outputs single
% solution.
% For example: my_mul(12, 2, 3, 5) gives ans = 360
if nargout >=1
disp('Error, wrong number of output arguments');
varargout{1} = 0;
return
end
if nargin <= 1
disp('Error, small number of input argumnets');
return
else
muln = 1;
for i = 1:nargin
muln = muln*varargin{i};
end
end
end
Hi, everyone, I'm just doing my assignment for uni and have a qiuck question.
How can I make this function to give an error if it is called with more than one output.(It meant to give only one) Thanks!
In your function definition, you have defined your function to allow for an unlimited number of outputs. The keyword varargout is a place-holder for a variable number of outputs.
As you have stated in your question, you only want one possible output which in your case looks to be muln. So if you simply remove varargout from your function definition, MATLAB should automatically throw an error if too many outputs are requested
function muln = my_mul(varargin)
If you ever do need to use varargout but want to place constraints on how many outputs are provided for any given scenario, you can check the number of output arguments that were requested using nargout and then throw an error with the error function.
if nargout > 4
error('my_mul:TooManyOutputs', 'Too many outputs requested');
end
My opinion is that if a return value is expected the function needs to throw. Otherwise the caller (function calling this function) will expect everything to be ok. Note that disp('Error') gives information to the developer, but it does not give the program any indication on what happens. More importantly, the information does not give any indication of where the error occurs. This can force the developer to do heavy debugging just to find the error, which is completely unnecessary.
The use of variable output arguments should only be used in case a different number of output arguments should be expected. An example is some customized plot function
function varargout = myplot(varargin)
filename = '';
idx = find(strcmp(varargin,'filename'));
if (~isempty(idx) && length(varargin)<idx+1 && ~ischar(varargin{idx+1}))
error('filename property must be followed by a directory');
elseif(~isempty(idx))
filename = varargin{idx+1};
varargin([idx,idx+1]) = [];
end
h = plot(varargin{:});
varagout{1} = h;
if (~isempty(idx))
save(filename, h);
end
varagout{2} = filename;
This function works as plot except it saves the figure to file in case a filename is specified. In case the developer needs the handle it will be returned and in case the developer wants the save directory it can be returned as well. None of these arguments are necessary though. The developer may want to use this function as a standard plot function and this means that the user may want to call myplot as myplot(x,y);which does not return a value. Further note that even if 'filename' is not specified, the function can still return 2 outputs. The second output may be an empty array of char, but two outputs for the caller will never cause a crash.
Also, note that no further error handling is required. The only unchecked crashes are in plot and save. How this is handled may be different for different users and this means that it only is reasonable to let the user catch the error and handle it (as he would have done if save or plot would have thrown).
Apart from this you may also want to have a check so that the number of output variables are within the correct range (in this case 0,1 or 2 outputs).
This is NOT a question where I need to know how to add A+B in MATLAB. This is more of a code design question.
I have few function files that return a numeric matrix and index info on the matrix. For example
function [Mat1, IdxID, IdxDate, IdxVal, IdxMarker, IdxOpen, ...] = First ()
....
.... % where IdxId = 1 ; IdxDate = 2 ; ...
end
function [Mat1, IdxUid, IdxName, IdxVal, Mat2, IdxUid2, IdxSalary2, ...] = Second ()
....
.... % where IdxUid= 1 ; IdxName= 2 ; ...
end
As you can see the code becomes clunky and when I call these functions, I have to declare an equal number of outputs to catch all the indices. The advantage is if I suddenly swap ID & Date columns, the calling functions do not change as I simply make ID=2, Date=1. I also have the advantage of renaming these variables inside the function.
Is there a better way to do this? I'm testing whether struct or cell can be used for indices. I can't use datasets or cell for returning numeric matrix. Too much time is lost in translating it into numbers. Thanks.
Yes, you can return arrays/cells/structs instead. For instance, id can be a struct with multiple variables. Your function definition could be as follows.
function [Mat, Id] = Second ()
...
end
In your function, have the following set:
Id.Name
Id.Val
Id.Salary
...
If you find that you have multiple structs with the same exact structure, you can even consider objects.
Please clarify with more details on the structure if you want a more detailed answer.
Can anyone tell me how to compare this for loop array value pp1 with the single value of pp. If the value of pp is present in pp1 then it must show 1 or must show 0. I'm getting 1 only the last value of pp1. The code is:
[pp,pf1]=pitchauto(x,fs);
for ix=1:2
V='.wav';
ie=num2str(ix);
Stc=strcat(ie,V);
[x1,fs1]=wavread(Stc);
figure,plot(x1);
title('Test Audio');
[pp1,pf1]=pitchauto(x1,fs1);
end
if (pp==pp1)
msgbox('Matching');
else
msgbox('Not Matching');
end
Kindly do reply with the correct answers.
You calculate a value for pp1 each time, do nothing with it, then let the next loop iteration overwrite it. To make use of it, either put the test inside the loop:
for ix=1:2
V='.wav';
ie=num2str(ix);
Stc=strcat(ie,V);
[x1,fs1]=wavread(Stc);
figure,plot(x1);
title('Test Audio');
[pp1,pf1]=pitchauto(x1,fs1);
if (pp==pp1)
msgbox('Matching', num2str(ix)); % show the index number as msgbox title
else
msgbox('Not Matching', num2str(ix));
end
end
or collect the values of pp1 in an array to test afterwards:
for ix=1:2
V='.wav';
ie=num2str(ix);
Stc=strcat(ie,V);
[x1,fs1]=wavread(Stc);
figure,plot(x1);
title('Test Audio');
[pp1(ix),pf1]=pitchauto(x1,fs1); % assuming pitchauto returns a scalar
end
matchidx = (pp == pp1);
if any(matchidx)
msgbox(strcat('Matching indices: ', num2str(find(matchidx))));
else
msgbox('Not Matching');
end
If the values aren't scalar, then this approach is a bit more difficult - you could still use a matrix to collect equal-sized vectors, or a cell array to collect anything - but it's probably easier to stick with the first approach in that case.
I have written a simple class in MATLAB to manage a set of key-value pairs. I would like to be able to access the keys using a dot after the object name like:
params.maxIterations
instead of:
params.get('maxIterations')
Is it possible to override the dot operator so that it calls my get() method?
I have tried to override the subsasgn() method as suggested here but I couldn't figure out how I should write it.
You could use dynamic properties. Then instead of adding a list of strings, you add a new property for each 'key'. Get all keys with properties(MyClass) (of just fieldnames(MyClass)
However, I think it's indeed best to overload subsref, but note that doing that properly can eat away the majority of a work week if you do it for the first time...It's not that it's really difficult, it's just that the () operator does so much :)
Luckily, you don't have to. Here's how:
classdef MyClass < handle
methods
function result = subsref(obj, S)
%// Properly overloading the () operator is *DIFFICULT*!!
%// Therefore, delegate everything to the built-in function,
%// except for 1 isolated case:
try
if ~strcmp(S.type, '()') || ...
~all(cellfun('isclass', S.subs, 'char'))
result = builtin('subsref', obj, S);
else
keys = S.subs %// Note: cellstring;
%// could contain multiple keys
%// ...and do whatever you want with it
end
catch ME
%// (this construction makes it less apparent that the
%// operator was overloaded)
throwAsCaller(ME);
end
end % subsref method
end % methods
end % class