Integrating function with two variables in Matlab - matlab

Hey I'm having trouble integrating a function in MATLAB, constantly getting errors. I'm trying to fill a matrix with the function. exp(x-1)*x^j+k
I2 = zeros(26,3);
k = [0.13, 0.0024, 0.000035];
for i = 1:length(k)
for j = 0:25
fun = #(x,j) exp(x-1).*x.^j+k(i);
I2(j,i) = integral(fun,0,1);
end %end j-loop
end %end i-loop
display(I2);
Thanks.

In the current form the function handle is expecting two inputs but you want a function with a single input for integral. Changing your function handle definition to the following should fix this.
fun = #(x) exp(x-1)*x^j+k(i);

Related

Undefined function or variable 'resubPredict'. Why?

I have MATLAB R2015b and I am working on a Pattern Recognition project. I have loaded fisher iris data set.
I have written the code below for k-NN classification:
rng default;
fold_number = 5;
indices = crossvalind('Kfold',species, fold_number);
val = 1:2:5; % for these small k values there will not be an important difference
% regarding the cp ErrorRates. The difference is going to be
% observable for val = 1:2:100, for example!!! But the
% exercise asks only for k = 1,3,5.
err_arr = [];
for k=val
cp = classperf(species); % Reinitialize the cp-structure!
for i = 1:fold_number
test = (indices == i);
train = ~test;
class = knnclassify(meas(test,:),meas(train,:),species(train), k);
%class = knnclassify(meas(test,2),meas(train,2),species(train), k); % To experiment only with the 2nd feature
classperf(cp,class,test);
end
err_arr = [err_arr; cp.ErrorRate];
fprintf('The k-NN classification error rate for k = %d is: %f\n', k,cp.ErrorRate);
end
fprintf('\n The error array is: \n');
disp(err_arr);
fprintf('Program paused. Press enter to continue.\n');
pause
After that, I would like to plot the confusion matrix. So, I need this line of code:
[C,order] = confusionmat(species, predicted_species);
So, I have to find the predicted_species matrix. I have thought to write the below line of code about that:
predicted_species = resubPredict(class);
Here is the moment I am getting the on the title mentioned error and I do not know why, while resubPredict is a function supported by my MATLAB version.
Could anyone help me solve this problem?
Take a look at the top of the documentation for resubPredict, there you will notice the line
Class ClassificationKNN
Meaning that the function can only be used with inputs of that type. In your case you are passing doubles.
You have to switch to the new interface, fitcknn instead of knnclassify

Expected scalar value: MATLAB Coder

I get the following error while using MATLAB coder for generating a c++ code from m file with a call to a c function ompmex.c
C function calls always return scalar values but a non-scalar value is expected here.
My code is:
function [D,gamma] = DSGD2(X,H) %#codegen
[Xr,Xc]=size(X);
[Hr,Hc]=size(H);
D=zeros(Hr,Hc,'double');
D=X(:,11:210);
d1=sqrt(sum(D.*D)); D=D./repmat(d1,Xr,1);
beta=zeros(Xr,Xc,'double');
beta=coder.ceval('ompmex',H,X,H'*H,200);
Can anybody help on this. I am not getting a working answer online
function [D,gamma] = DSGD2(X,H) %#codegen
[Xr,Xc] = size(X);
[Hr,Hc] = size(H);
D = zeros(Hr,Hc,'double');
D = X(:,11:210);
d1 = sqrt(sum(D.*D));
D = D./repmat(d1,Xr,1);
% coder.ceval is tricky. I recommand to use it only if the function is
% created by c-coder too (and not as mex function!)! you need a c executable
% or a c library (generated before you trigger codegen for DSGD2).
% further more, ceval can not handle multiple
% outputs. as a workaround, always use structs for output - and for
% input too!
s = struct('beta',(zeros(Xr,Xc,'double')));
% make it work in matlab too and call ompmex function
if coder.target('MATLAB')
s = ompmex(H,X,H'*H,200);
else
coder.ceval('ompmex_initialize')
s = coder.ceval('ompmex',H,X,H'*H,200);
coder.ceval('ompmex_terminate')
end
% read out stuct value
beta = zeros(Xr,Xc,'double');
beta = s.beta;
gamma = 0; % not given by you, but c-coder needs it. so change to what ever you need
end

Conversion function for 3D value into 2D in MATLAB

I have written a function for converting 3D values into 2D, but not able to get it working may be I am parsing the wrong values.
I am passing the value in the valuse as 2 coordinates and trying to get into Output in 2D. Can anyone please do the correction in the function below and help me in running the function?
% Perspective Projection
function Output = perspective_projection(Input)
Output = zeros(size(Input));
for ii = 1: length(Input)
Output(ii,1) = Input(ii,1)/Input(ii,3);
Output(ii,2)=Input(ii,2)/Input(ii,3);
end
value = [6,4,2];
[a1,b1] = perspective_projection(a1)
BSXFUN method as suggested by Rody is an elegant way, but if you would like to keep your loop, try this -
% Perspective Projection
function Output = perspective_projection(Input)
Output = zeros(size(Input,1),2);
for ii = 1: size(Input,1)
Output(ii,1) = Input(ii,1)/Input(ii,3);
Output(ii,2) = Input(ii,2)/Input(ii,3);
end
If I understand you correctly, you should rewrite your function as:
function Output = perspective_projection(Input)
Output = bsxfun(#rdivide, Input(:,1:2), Input(:,3));
end
or, judging from the way you seem to be calling it:
function [OutputX,OutputY] = perspective_projection(Input)
OutputX = Input(:,1)./Input(:,3);
OutputY = Input(:,2)./Input(:,3);
end
Note that your function is quite simple (I wouldn't even use a function):
[X,Y] = deal(Input(:,1)./Input(:,3), Input(:,2)./Input(:,3));
As for your original function: the error is in the initialization:
function Output = perspective_projection(Input)
%// WRONG: this initializes a 3D array!
Output = zeros(size(Input));
%// ...but you want a 2D array
for ii = 1: length(Input)
Output(ii,1) = Input(ii,1)/Input(ii,3);
Output(ii,2) = Input(ii,2)/Input(ii,3);
end
end
and of course, the multiple outputs (but it's not quite clear to me whether you want that or not...)

First input must be function handle error using arrayfun()

I'm trying to use arrayfun() to map a function over a cell array. The following is happening:
>> arrayfun(solveFunc, equArray)
Error using arrayfun
First input must be a function handle.
Error in solve>genGuess (line 33)
funcVals = abs(arrayfun(inFunc, xValues));
Error in solve (line 8)
x = genGuess(inFunc, varargin{1}, varargin{2});
Error in makeSolveFunc>#(func)solve(func,start,stop) (line 3)
sFunc = #(func) solve(func, start, stop);
But, the first input IS a function handle. Also... if I manually apply the function to each element of the provided cell array, everything works fine:
>> solveFunc(equArray{1})
ans =
4.7335
>> solveFunc(equArray{2})
ans =
4.7356
Does anyone know why this would be happening? I assumed that if I could manually apply the function to each element of my array, and the return type of the function was consistent and one of the allowed types (you can't for example have arrayfun return an array of function handles... I already tried doing that), it should work. Perhaps that is not the only requirement.
Here is some code that generates this error:
solve.m
function solution = solve(inFunc, start, stop)
%SOLVE solve an equation using Newton's Method
x = genGuess(inFunc, start, stop);
for i = 1:100
m = getSlope(inFunc, x);
x = (m*x - inFunc(x))/m;
end
solution = x;
end
function slope = getSlope(inFunc, x)
%SLOPE calculate the slope at a given point
inc = 1e-5;
if x ~= 0
inc = inc * x;
end
slope = (inFunc(x + inc) - inFunc(x - inc))/(2*inc);
end
function guess = genGuess(inFunc, start, stop)
%GENGUESS get an initial guess to the solution
xValues = linspace(start, stop, 101);
funcVals = abs(arrayfun(inFunc, xValues));
[~, minIndex] = min(funcVals);
guess = xValues(minIndex);
end
charEqu.m
function equ = charEqu(a)
%CHAREQU create a KP model characteristic equation with provided p
equ = #(x) x + a;
end
makeSolveFunc.m
function sFunc = makeSolveFunc(start, stop)
%MAKESOLVEFUNC return a function that solves an equation
sFunc = #(func) solve(func, start, stop);
end
test.m
pArray = 1:5;
equArray = cell(1,arrayLen);
for i = 1:5
equArray{i} = charEqu(pArray(i));
end
solveFunc = makeSolveFunc(1.1*pi, 2*pi);
alphaAArray = arrayfun(solveFunc, equArray);
I have narrowed down the error to something in genGuess(). For some reason, in the line funcVals = abs(arrayfun(inFunc, xValues)); the variable inFunc is a 1x1 cell array containing a function handle. I have no idea why that would be the case. I traced this back to the anonymous function call #(func) solve(func, start, stop); in the makeSolveFunc() function. There it is still a 1x1 cell array containing a function handle. I'm not really sure where that cell array is coming from as that function is getting called from arrayfun().
Background information on what I'm trying to do in case someone wants to suggest a better way:
I'm trying to solve equations using Newton's method. I have written a function that can solve an equation given an initial guess range. This function is the solve() function you can see in the first error message. It takes a function, and the guess range and returns a function that I'm calling solveFunc(). solveFunc() takes a function and solves it using the initial guess range previously provided.
Maybe I'm just too used to functional programming and should just use a loop.
If the arguments passed to the function handle are contents of elements of a cell array, you need to use cellfun instead of arrayfun:
cellfun(solveFunc, equArray)
This is equivalent to
for i=1:length(equArray)
out(i) = solveFunc(equArray{i});
end
since solveFunc is already a function handle.
Check where the error comes from. This line causes the error:
funcVals = abs(arrayfun(inFunc, xValues));
The first input argument is a 1x1 cell containing one function handle. This is caused because equArray is a cell, thus use cellfun as Jonas already mentioned:
pArray = 1:5;
equArray = cell(1,arrayLen);
for i = 1:5
equArray{i} = charEqu(pArray(i));
end
solveFunc = makeSolveFunc(1.1*pi, 2*pi);
alphaAArray = cellfun(solveFunc, equArray);

Use MATLAB's 'keyPressFcn' in a simple program

I am trying to use the 'KeyPressFcn' in a normal MATLAB script, but I am having problems. I can use it nicely WITHIN a function, (like here), but I would like to use it in a normal script like so.
My simple script is:
%Entry Point
clear all
N = 100;
x = randn(1,N);
figHandle = figure(1);
clf(figHandle);
set(figHandle, 'KeyPressFcn', myFunction(~, eventDat,x,N))
Here is the function 'myFunction' that sits in the same directory:
function myFunction(~, eventDat,x,N)
mean = sum(x)/N;
disp(mean);
key = eventDat.Key;
disp(key);
end
Now, if I run this, it does not work, because, (I suspect), something is wrong with the way I am calling myFunction, but I cannot figure out what the problem is exactly, since I am a noob at using KeyPressFcn. Help would be appreciated for this problem. Thanks!
You need to do it through anonymous functions:
In script file, for example called test.m:
%Entry Point
clear all
N = 100;
x = randn(1,N);
figHandle = figure(1);
clf(figHandle);
set(figHandle, 'KeyPressFcn', ...
#(fig_obj , eventDat) myFunction(fig_obj, eventDat, x, N));
In a file called myFunction.m in the same folder as test.m
function myFunction(~, eventDat, x, N)
mean = sum(x)/N;
disp(mean);
key = eventDat.Key;
disp(key);
How to return value from myFunction?
There are few ways of doing this. It depends on what u want to do. But quickly you could use mutable variables for this, such as, containers.Map. This is one example of ding this. The returned variable is newN.
In script file, for example called test.m:
%Entry Point
clear all
N = 100;
x = randn(1,N);
% this map will store everything u want to return from myFunction.
returnMap = containers.Map;
figHandle = figure(1);
clf(figHandle);
set(figHandle, 'KeyPressFcn', ...
#(fig_obj , eventDat) myFunction(fig_obj, eventDat, x, N, returnMap));
% wait till gui finishes in this example.
waitfor(figHandle);
newN = returnMap('newN');
% display newN
newN
In a file called myFunction.m:
function myFunction(handle, eventDat, x, N, returnMap)
mean = sum(x)/N;
disp(mean);
key = eventDat.Key;
disp(key);
newN = 435;
returnMap('newN') = newN;