Title said it the most, but more specifically the question begin asked is...
"Your function should keep track of the number of times that it has been called
Your function will accept 1, 5 or 6 arguments and return 1, 2 or 3 values
All arguments must be either a scalar or a row matrix; you should check for this and print
an error message and return with a 0 in the first return value if it is not true.
All arguments must be the same size: either they all must be scalars or they all must be
row vectors of the same length. You must check for this and print an error message and
return with a 0 in the first return value if it is not true"
Thats not the whole problem i assure you, but the part at which i struggle with the most. As in, i have no idea how to keep track of the number of times it's been called (with count maybe?) or have any idea how to check the argument whether or not this is a scalar or a row matrix. Also checking whether or not if they are the same size
I search up on how to do all this, no result. So therefore, i am going to assume this is not the basics.
This is all basic stuff you just didn't search hard enough:
Keep track of the number of times with a global variable. Just increment it each time the function is entered. Alternitivly you can get a workspace variable with assignin and eval: HERE for Global. HERE for assignin. HERE for eval.
Check input arguments with nargin which can be used to pass the inputs: HERE
Differing number of outputs with varargout: HERE
Use size or length to check the length of inputs. disp to display a message, set the first output and use return to return.
Hope this helps.
Related
I am trying to write a function which returns a value 1 if the number entered is a power of two, else it returns a value 0.
function val = func_1(num)
while not(num == 1)
if num%2~=0
val=0;
break
end
num=num/2;
val=1;
end
end
But unfortunately, the function always return a value 1. Is there any error in the algorithm or the code? Thanks in advance for any help.
In Matlab, % is the comment character. Everything from that point onwards until the end of the line is ignored. This means that this line if num%2~=0 is not doing what you think it does.
Instead, use the mod function. link. In this case, the line in question becomes if mod(num, 2)~=0.
On a separate note, I suspect there is a much more efficient way of doing this. See, for example, here.
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.
Suppose I have a function that gives out unknown number of output arguments (it depends on input,thus change through the loops). How to get all of them?
nargout doesn't help as the function uses varargout (the result is -1)
And of course I can't rewrite the function, otherwise the question wouldn't arise :- )
Well, thanks to all partisipated in discussion. Summing up, it seems the problem has no general solution, because MatLab itself estimates the number of desired outputs before the function call to use inside it. Three cases can be pointed out though:
1) The funcrion doesn't have varargout in definition, thus nOut=nargout(#fcn) returns positive number.
Then nOut is an actual number of outputs and we can use a cell array and a column list trick.
X=cell(1,nOut);
[X{:}]=fcn(inputs);
2) The funcrion has varargout in definition, thus nOut=nargout(#fcn) returns negative number. However some correlation with inputs can be found (like length(varargin)=length(varargout)).
Then we can calculate the resulting nOut from inputs and perform the above column list trick.
3) You know the fcn developer.
Ask him fot assistance. For example to make the function's output to be a cell array.
One of ways I usually use in this case is to store all outputs in a cell array inside the function. Getting the cell array outside the function's body, you might investigate its length and other properties.
Here is how you could deal with the problem in general. I didn't mention this solution earlier because... it is horrible.
Suppose a function can have 1 or 2 output arguments:
try
[a, b] = f(x)
catch
a = f(x)
end
Of course it is possible to do this for any number of output arguments, but you really don't want to.
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(...
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.