Matlab recursion - matlab

Need a little help understanding what is happening in this function particularly line 7 [Fnm1,Fnm2] = fibrecurmemo(N-1); I don't understand how a new variable can be declared here with in the array. an example of what is happening would be appreciated.
function [Fn,Fnm1] = fibrecurmemo(N)
% Computes the Fibonacci number, F(N), using a memoized recursion
if N <= 2
Fn = 1;
Fnm1 = 1;
else
[Fnm1,Fnm2] = fibrecurmemo(N-1);
Fn = Fnm1 + Fnm2;
end
end

Say we start with:
fibrecurmemo(3) %// N is 3
The else statements run (since N > 2):
[Fnm1,Fnm2] = fibrecurmemo(2); %//statement 1
Fn = Fnm1 + Fnm2; %//statement 2
Before statement 2 can run, fibrecurmemo(2) must first run.
The if statements in fibrecurmemo(2) run (since N <= 2):
Fn = 1;
Fnm1 = 1;
As a result, fibrecurmemo(2) returns 1, 1.
Contininuing from statement 1 above,
[1,1] = fibrecurmemo(2); %//statement 1
Fn = 1 + 1; %//statement 2
Finally,
[2, 1] = fibrecurmemo(3);

The function returns two values.
function [xFive,yFive] = addFive(x,y)
xFive = x + 5;
yFive = y + 5;
end
xx = (addFive(3,4))
xx will be equal to 8 in this example
the syntax for assignment for multiple return values is
[a,b,c,...] = someFunc();
where someFunc() has output of [a,b,c,...]
[aa,bb] = addFive(3,4);
cc = addFive(3,4);
if you do it this way you would get
aa == 8
bb == 9
cc == 8
in the case of cc instead of [aa,bb] Then you will just get the first return value.
i.e. you could do
x = fibrecurmemo(5)
[y,z] = fibrecurmemo(5)
in this case x == y

Related

Using custom functions in blockproc in Matlab

I wanted to use my own (custom) function in blockproc function. But I am not able to figure out how to actually incorporate this. I am new to MATLAB.
In this function I am trying to embed info (the bits of LR_seq) into the block. I am selecting a pair of pixels at a time in the block and trying to embed my info into it.
This is the code of my function:
function dataencode(block_struct,LR_seq)
LR_seq = vec2mat(LR_seq,2,4);%changing it into a 2,4 mat to make it fit into the for loop
LR_mat = zeros(4,4);%adding zero columns in between to convert it into 4,4 mat to fit into the for loop
LR_mat(:,1:2:end) = LR_seq;
for r = 1 : 4
for c = [1 3]
x = uint16(block_struct.data(r,c)) ;
y = uint16(block_struct.data(r,c+1));
x1 = de2bi(x,12); y1 = de2bi(y,12);
if(~(2*x - y == 1) | ~(2*y - x == 1) | ~(2*x - y == 255) | ~(2*y - x == 255))
if((x1(1) == 0) & (y1(1) == 0)) %because in maltab lsb comes first
xt = (2*x - y) ; yt = (2*y - x);
xt_bin = de2bi(xt,12); xt_bin(1) = 1; xtd = bi2de(xt_bin);block_struct.data(r,c) =xtd;
yt_bin = de2bi(yt,12) ; yt_bin(1) = LR_mat(r,c); ytd = bi2de(yt_bin); block_struct.data(r,c+1) = ytd;
elseif((x1(1) == 1) | (y1(1) == 1))
x1(1) = 0 ; xtd = bi2de(x1) ; block.data(r,c) = xtd;
y1(1) = LR_mat(r,c); ytd = bi2de(y1) ; block_struct.data(r,c+1) = ytd;
end
else
x1(1) = 0; xtd = bi2de(x1) ; block.data(r,c) = xtd;
ytd = bi2de(y1); block_struct.data(r,c+1) = ytd;
end
end
end
end
M is a RGB 256x256 image in which I want to embed the sequence of bits LR_seq.
I am trying to call this function in the command window but it is giving me a empty matrix, please help out. This is my code for calling the function
for ii = 1 : 8 : size(LR_seq)
myfunc = #(block_struct) dataencode(block_struct,LR_seq(ii : ii+7));
U_im_new = blockproc(M,[4 4],myfunc)
end
dataencode should take a block_struct in parameter. But your function myfunc_red calls the encode function with the data of the block_struct.
You may prefer to do this:
myfunc = #(block_struct) dataencode(block_struct,LR_seq(1 : 8));
U_im_r = blockproc(M(:,:,1),[4 4],myfunc);

Compute sum of series

I need to compute the sum of this series
I need the output this way:
If n = 3;
x = function_name(n)
I need to get x = 11.
If n = 5;
x = function_name(n)
I need to get x = 45.
I believe I need a for-loop to iterate; but am finding it difficult to iterate the increment value itself.
I guess you want the sum of the cumsum of the differences d of the numbers:
d = 2;
n = 5;
s = d:d:d*(n-1)
cs = cumsum( [1 s] )
scs = sum(cs)
%// or as anonymous function
scsh = #(n,d) sum( cumsum( [1 d:d:d*(n-1)] ) )
scs =
45
scsh(5,2) =
45
No need for a loop!
inc=2;
sum=1;
next=1;
n=input('what is n?\n');
for i=2:n
next=next+inc;
sum=sum+next;
inc=inc+2;
end
disp('sum is ');
disp(sum);
function Total = abc(n)
nth_term=1;
Total = 1 ;
for d = 2:2:(2*(n-1))
nth_term = nth_term + d;
Total =Total + nth_term;
end
end

vectorizing function in octave / matlab

I have a function that I was wondering if it was possible to vectorize it and not have to use a for loop. The code is below.
a=1:2:8
for jj=1:length(a)
b(jj)=rtfib(a(jj)); %fibbonacci function
end
b
output below:
a =
1 3 5 7
>>>b =
1 3 8 21
I was trying to do it this way
t = 0:.01:10;
y = sin(t);
but doing the code below doesn't work any suggestions?
ps: I'm trying to keep the function rtfib because of it's speed and I need to use very large Fibonacci numbers. I'm using octave 3.8.1
a=1:2:8
b=rtfib(a)
Here's the rtfib code below as requested
function f = rtfib(n)
if (n == 0)
f = 0;
elseif (n==1)
f=1;
elseif (n == 2)
f = 2;
else
fOld = 2;
fOlder = 1;
for i = 3 : n
f = fOld + fOlder;
fOlder = fOld;
fOld = f;
end
end
end
You can see that your function rtfib actually computes every Fibonacci number up to n.
You can modify it so that is stores and returns all these number, so that you only have to call the function once with the maximum number you need:
function f = rtfib(n)
f=zeros(1,n+1);
if (n >= 0)
f(1) = 0;
end
if (n>=1)
f(2)=1;
end
if (n >= 2)
f(3) = 2;
end
if n>2
fOld = 2;
fOlder = 1;
for i = 3 : n
f(i+1) = fOld + fOlder;
fOlder = fOld;
fOld = f(i+1);
end
end
end
(It will return fibonnaci(n) in f(n+1), if you don't need the 0 you could change it so that it returns fibonnaci(n) in f(n) if you prefer)
Then you only need to call
>>f=rtfib(max(a));
>>b=f(a+1)
b =
1 3 8 21
If you don't want to store everything you could modify the function rtfib a little more, so that it takes the the array a as input, compute the Fibonacci numbers up to max(a) but only stores the one needed, and it would directly return b.
Both solutions will slow down rtfib itself but it will be a lot faster than calculating the Fibonacci numbers from 0 each time.

Recursive Function to generate / print a Fibonacci series

I am trying to create a recursive function call method that would print the Fibonacci until a specific location:
1 function f = fibonacci(n)
2 fprintf('The value is %d\n', n)
3 if (n==1)
4 f(1) = 1;
5 return;
6 elseif (n == 2)
7 f(2) = 2;
8 else
9 f(n) = fibonacci(n-1) + fibonacci(n-2);
10 end
11 end
As per my understanding the fibonacci function would be called recursively until value of argument n passed to it is 1. Then the function stack would rollback accordingly. So when I call this function from command:
>> fibonacci(4)
The value of n is 4, so line 9 would execute like:
9 f(4) = fibonacci(3) + fibonacci(2);
Now I believe that that first fibonacci(3) would be called - hence again for fibonacci(3)
9 if(3) = fibonacci(2) + fibonacci(1);
The ifs in line number 3 and 6 would take care.
But now how fibonacci(2) + fibonacci(1) statement would change to:
if(3) = 2 + 1;
I am receiving the below error and unable to debug further to resolve it:
>> fibonacci(4)
The value is 4
The value is 3
The value is 2
The value is 1
In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in fibonacci (line 9)
f(n) = fibonacci(n-1) + fibonacci(n-2);
Error in fibonacci (line 9)
f(n) = fibonacci(n-1) + fibonacci(n-2);
Please provide some insight for the solution and with which parameter would fibonacci function be recursively called at line number 9 first and consequently.
Ex For n = 4
f(n) = fibonacci(3) + fibonacci(2);
So will MATLAB call fibonacci(3) or fibonacci(2) first?
Shouldn't the code be some thing like below:
1 function f = fibonacci(n)
2 fprintf('The valus is %d\n', n)
3 if (n==1)
4 f(1) = 1;
5 return f(1);
6 elseif (n == 2)
7 f(2) = 2;
8 return f(2);
9 else
10 f(n) = fibonacci(n-1) + fibonacci(n-2);
11 end
12 end
fibonacci(4)
Error: File: fibonacci.m Line: 5 Column: 12
Unexpected MATLAB expression.
Why return expression in a function is resulting in an error?
Try this:
function f = fibonacci(n)
if (n==1)
f= 1;
elseif (n == 2)
f = 2;
else
f = fibonacci(n-1) + fibonacci(n-2);
end
Note that this is also a recursion (that only evaluates each n once):
function f=fibonacci(n)
f=additive(n,1,2);
function a=additive(n,x0,x1)
if(n==1)
a=x0;
else
if(n==2)
a=x1;
else
a=additive(n-1,x1,x0+x1);
end
end
If you HAVE to use recursive approach, try this -
function out = fibonacci(n)
fprintf('The valus is %d\n', n)
if (n==1)
out = 1;
return;
elseif (n == 2)
out = 2;
return;
else
out = fibonacci(n-1) + fibonacci(n-2);
end
return;
Unlike C/C++, in MATLAB with 'return', one can't return a value, but only the control goes back to the calling function. The output to be returned to the calling function is to be stored in the output variable that is defined at the start of the function.
EDIT 1: For the entire fibonacci series and which assumes that the series starts from 1, use this -
N = 16; %// Number of fibonacci numbers needed
all_nums = zeros(1,N);
all_nums(1) = 1;
for k = 2:N
all_nums(k) = fibonacci(k-1);
end
Gives -
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Create a M-file for fibonacci function and write code as given below
function [ result ] = fibonacci( n )
if n==0|n==1
result = n;
else
result = fibonacci(n-2)+fibonacci(n-1);
end
end
Write following code in command window of matlab
for n = 0:10
fprintf('Fibonacci(%d)= %d\n', n, fibonacci(n));
end
Output :-
Fibonacci(0)= 0
Fibonacci(1)= 1
Fibonacci(2)= 1
Fibonacci(3)= 2
Fibonacci(4)= 3
Fibonacci(5)= 5
Fibonacci(6)= 8
Fibonacci(7)= 13
Fibonacci(8)= 21
Fibonacci(9)= 34
Fibonacci(10)= 55
Create a function, which returns Integer:
func fibonacci(number n : Int) -> Int
{
guard n > 1 else {return n}
return fibonacci(number: n-1) + fibonacci(number: n-2)
}
This will return the fibonacci output of n numbers, To print the series You can use this function like this in swift:
for _ in 0...10
{
print(fibonacci(number : 10))
}
It will print the series of 10 numbers.

Counting Number of Specific Outputs of a Function

If I have a matrix and I want to apply a function to each row of the matrix. This function has three possible outputs, either x = 0, x = 1, or x > 0. There's a couple things I'm running into trouble with...
1) The cases that output x = 1 or x > 0 are different and I'm not sure how to differentiate between the two when writing my script.
2) My function isn't counting correctly? I think this might be a problem with how I have my loop set up?
This is what I've come up with. Logically, I feel like this should work (except for the hiccup w/ the first problem I've stated)
[m n] = size(matrix);
a = 0; b = 0; c = 0;
for i = 1 : m
x(i) = function(matrix(m,:));
if x > 0
a = a + 1;
end
if x == 0
b = b + 1;
end
if x == 1
c = c + 1;
end
end
First you probably have an error in line 4. It probably should be i instead of m.
x(i) = function(matrix(i,:));
You can calculate a, b and c out of the loop:
a = sum(x>0);
b = sum(x==0);
c = sum(x==1);
If you want to distinguish x==1 and x>0 then may be with sum(xor(x==1,x>0)).
Also you may have problem with precision error when comparing double values with 0 and 1.