Fibonacci Function in MATLAB - matlab

I am attempting to create a function for the Fibonacci numbers using a for loop. My code is as follows:
function fib = fibGenerator(N)
fib(1) = 0;
fib(2) = 1;
for i = 3:N
fib(i) = fib(i-1)+fib(i-2);
end
The following error message is displayed: Variable fib must be of data type uint32. It is currently of type double. Check where the variable is assigned a value.
I'm unsure of how to correct this.
Update
function fib = fibGenerator(N)
fibGenerator(1) = uint32(0);
fibGenerator(2) = uint32(1);
for i = 3:N
fibGenerator(i) = fibGenerator(i-1)+fibGenerator(i-2);
end

You have to cast when you initially create fib: fib(1) = uint32(0);
Here is an example demonstrating this. When creating x you decide the type. Even if later assignments are double or of other types, it will keep its type.
>> x=uint32(1)
x =
uint32
1
>> x(2)=double(2)
x =
1×2 uint32 row vector
1 2

Related

Matlab: function handle in cell array with undefined operators

When I try to run this code I get the following error: "Undefined operator '.*' for input arguments of type 'cell'." My goal here is to build an array (cell array since I'm working with function handles) via a for loop and take the integral of each element of the resulting array. The error occurs on the last line. I'm trying to plug in the value 1.5 for every element in the array. Any tips on how to "handle" this error?
FUN_1 = #(y_1,y_2,x_1,x_2)sum(heaviside(y_1-a_k(1:m,1)).*dirac(1,y_2-a_k(1:m,2))).*(-1/2.*log((x_1-y_1).^2+(x_2-y_2).^2))+(x_1-y_1).^2./((x_1-y_1).^2)+sum(dirac(y_1-a_k(1:m,1)).*dirac(y_2-a_k(1:m,2))).*(-1/2.*log((x_1-y_1).^2+(x_2-y_2).^2))+(x_1-y_1).*(x_2-y_2)./((x_1-y_1).^2+(x_2-y_2).^2);
Q_1 = #(x_1,x_2)integral2(#(y_1,y_2)FUN_1(y_1,y_2,x_1,x_2),a(1,1),c(1,1),a(1,2),c(1,2));
FUN_2 = #(y_1,y_2,x_1,x_2)sum(heaviside(y_1-a_k(1:m,1)).*dirac(1,y_2-a_k(1:m,2))).*(-1/2.*log((x_1-y_1).^2+(x_2-y_2).^2))+(x_1-y_1).*(x_2-y_2)./((x_1-y_1).^2)+sum(dirac(y_1-a_k(1:m,1)).*dirac(y_2-a_k(1:m,2))).*(-1/2.*log((x_1-y_1).^2+(x_2-y_2).^2))+(x_2-y_2).^2./((x_1-y_1).^2+(x_2-y_2).^2);
Q_2 = #(x_1,x_2)integral2(#(y_1,y_2)FUN_1(y_1,y_2,x_1,x_2),a(1,1),c(1,1),a(1,2),c(1,2));
k = cell(1,2*M-1);
n=0;
for n = 0:2*M-1
k{1,n+1} = #(x_1,x_2)Q_1(x_1,x_2)*2*n*(x_1+1i*x_2)^(n-1)+ Q_2(x_1,x_2)*2*n*1i*(x_1+1i*x_2)^(n-1)]);
end
R = #(x_2)integral(#(x_1)k,a(1,1),c(1,1),'ArrayValued',true);
x= 1.5;
R{x}
I've updated the code as follows:
k = zeros(1,2*M);
n=0;
for n = 0:2*M-1
S = #(x_1,x_2)Q_1(x_1,x_2)*2*n*(x_1+1i*x_2)^(n-1) + Q_2(x_1,x_2)*2*n*1i*(x_1+1i*x_2)^(n-1);
R = #(x_2)integral(#(x_1)S,a(1,1),c(1,1));
k(1,n+1) = R(1);
end
disp(k);
but I'm still getting the following error:
"Input function must return 'double' or 'single' values. Found 'function_handle'.
for the line
k(1,n+1) = R(1);
Any tips?
In this line:
R = #(x_2) integral(#(x_1) S, a(1, 1), c(1, 1));
You aren't passing any values to S within your anonymous function #(x_1) S, so that anonymous function is just returning a function handle S instead of evaluating S for a set of inputs. I'm guessing you want to define it like this:
R = #(x_2) integral(#(x_1) S(x_1, x_2), a(1, 1), c(1, 1));

Conversion to struct from double is not possible

I have two questions
(1) Why is the following code generating this error ? where does double come from?
Error using horzcat
The following error occurred converting from double to struct:
Error using struct
Conversion to struct from double is not possible.
Error in remove_scratch (line 34)
old1 = [lines1, max_vertex1] ;
(2) how to get rid of this error?
Relevant Source Code
for n = 1:N
% take n-th image
hough_trf_input = monochrome_image(:,:,n);
% find straight lines in the image
[hough_lines, thetas] = hugh_transform(hough_trf_input);
%////////////////////////////////////////////////////////////
[lines1, max_vertex1] = find_lines(hough_lines, thetas(1));
[lines2, max_vertex2] = find_lines(hough_lines, thetas(2));
[lines3, max_vertex3] = find_lines(hough_lines, thetas(3));
if(n==1)
old1 = [lines1, max_vertex1];
old2 = [lines2, max_vertex2];
old3 = [lines3, max_vertex3];
else
oldlen1 = vertex_length(old1(2));
oldlen2 = vertex_length(old2(2));
oldlen3 = vertex_length(old3(2));
newlen1 = vertex_length(max_vertex1);
newlen2 = vertex_length(max_vertex2);
newlen3 = vertex_length(max_vertex3);
if(newlen1 > oldlen1)
old1 = [lines1, max_vertex1] ;
end
if(newlen2 > oldlen2)
old2 = [lines2, max_vertex2] ;
end
if(newlen3 > oldlen3)
old3 = [lines3, max_vertex3] ;
end
end
end
Here find_lines() returns a vector whose 1st element is a vector of line-structs, and the second element is a vector of two vectors where each vector is 2-element and represents an axis.
one of the variables {lines1, max_vertex1} is struct and the other is double. from their names I guess lines1 is struct and max_vertex1 is double. You can obtain the same error when running:
clear
% lines1 is struct
lines1.p1 = 1;
lines1.p2 = 1;
% max_vertex1 is double
max_vertex1 = 5;
old1 = [lines1, max_vertex1] ;
There are several ways to overcome this, for example you can extract the struct fields into double using struct2array:
old1 = [struct2array(lines1), max_vertex1] ;

matlab function inside while loop

I've created this small program just for simplicity of the question, I am having some trouble using my function inside a while loop
this is the script;
x = 1;
y = 1;
while x<10
y = func(x,y);
x = x + 1;
this is the function, func;
function [] = func(x,y)
y- exp(-x)
end
I get the error of
Error using func
Too many output arguments.
what am I doing wrong
When you declare the function:
function [] = func(x,y)
You have specified that there will be no return values, yet when you call it you require a return value:
y = func(x,y);
To fix this issue you must alter your function declaration, e.g.:
function y_out = func(x,y)
Also, within your function declaration you have y- exp(-x), which will not change the value of y; did you intend to have y=exp(-x)?

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

Is there a 'self' to refer own struct in MATLAB?

I'm grouping a set of anonymous functions into a structure and some variables within that structure. Is there a way to refer 'self', i.e, own structure? What I'd like to accomplish is to have a function returns some values based on the member variables. For simplicity, say I have a struct a, where
a.value_1 = 3;
a.value_2 = 2;
a.sum = #()(self.value_1 + self.value_2)
Is there something like that possible in MATLAB?
Before objected-oriented programming was introduced in MATLAB (including both classdef-style and the obsolete #-directory style classes), one could create lightweight objects using closures and nested functions (lacking inheritance of course). This concept also exists in other languages.
Here is an example:
function s = mystruct()
s = struct('value_1',[], 'value_2',2, 'sum',#mysum);
s.value_1 = 3;
function out = mysum()
out = s.value_1 + s.value_2;
end
end
Which is used as:
>> s = mystruct()
s =
value_1: 3
value_2: 2
sum: #mystruct/mysum
>> s.value_1 = 10; % NOTE: this wont do what you expect!
>> s.sum()
ans =
5
Note that variables are immediately captured when creating a closure (functions have their own private copy if you will). So if you change one of the exposed fields from the returned structure, it will not be reflected in the enclosed state (think of them as read-only properties).
One solution is to provide accessor methods:
function obj = mystruct()
% think of those as private properties
value_1 = 3;
value_2 = 2;
% returned object (this or self)
obj = struct();
% public accessors for properties
obj.value_1 = #accessValue1;
function out = accessValue1(in)
if nargin > 0, value_1 = in; end
out = value_1;
end
obj.value_2 = #accessValue2;
function out = accessValue2(in)
if nargin > 0, value_2 = in; end
out = value_2;
end
% member method
obj.sum = #mysum;
function out = mysum()
out = value_1 + value_2;
end
end
So now we could say:
>> s = mystruct()
s =
value_1: #mystruct/accessValue1
value_2: #mystruct/accessValue1
sum: #mystruct/mysum
>> x = s.value_1(); % get
>> s.value_1(10); % set
>> s.sum()
ans =
12
Which is starting to look like the current recommended approach to create classes:
classdef mystruct < handle
properties
value_1 = 3;
value_2 = 2;
end
methods
function out = sum(obj)
out = obj.value_1 + obj.value_2;
end
end
end
Used in a similar manner:
>> s = mystruct()
s =
mystruct with properties:
value_1: 3
value_2: 2
>> s.value_1 = 10;
>> s.sum
ans =
12
We could also define get/set access methods as before..
This seems to work but I think you should rather create a class than a struct to do this:
a.value_1 = 3;
a.value_2 = 2;
a.sum = #(x)(x.value_1 + x.value_2)
a.sum(a)
With this change
a.value_1 = 3;
a.value_2 = 2;
a.sum = #()(a.value_1 + a.value_2)
Then a.sum() returns 5. But what happens when you change one of the values, later on, e.g., set a.value_1 = 5? Now a.sum() returns ... still 5. The parameters passed into the anonymous function are evaluated upon instantiation. If you want the second behavior to work properly you need to use a class. See my answer to this question for more. The only reason to use a function handle like you have is to avoid evaluating and storing a large output of a function until it's needed.