Matlab recursion. Sum off all odd numbers in a vector - matlab

I am trying to implement a recursive function to add the odd numbers in a vector v.
So far this is my attempt
function result = sumOdd(v)
%sum of odd numbers in a vector v
%sumOdd(v)
n = 1;
odds = [];
if length(v) > 0
if mod(v(n),2) == 1
odds(n) = v(n);
v(n) = [];
n = n + 1;
sumOdd(v)
elseif mod(v(n),2) == 0
v(n) = [];
n = n + 1;
sumOdd(v)
end
else
disp(sum(odds))
end
end
This does not work and returns a value of zero. I am new to programming and recursion and would like to know what I'm doing wrong.
Thank you.

There is a better way to solve this in MATLAB:
function result=summOdd(v)
odd_numbers=v(mod(v,2)); % Use logical indexing to get all odd numbers
result=sum(odd_numbers); % Summ all numbers.
end
To give a recursive solution:
When implementing a recursive function, there is a pattern you should always follow. First start with the trivial case, where the recursion stops. In this case, the sum of an empty list is 0:
function result = sumOdd(v)
%sum of odd numbers in a vector v
%sumOdd(v)
if length(v) == 0
result=0;
else
%TBD
end
end
I always start this way to avoid infinite recursions when trying my code. Where the %TBD is placed you have to put your actual recursion. In this case your idea was to process the first element and put all remaining into the recursion. First write a variable s which contains 0 if the first element is even and the first element itself when it is odd. This way you can calculate the result using result=s+sumOdd(v)
function result = sumOdd(v)
%sum of odd numbers in a vector v
%sumOdd(v)
if length(v) == 0
result=0;
else
if mod(v(1),2) == 1
s=v(1);
else
s=0;
end
v(1) = [];
result=s+sumOdd(v);
end
end
Now having your code finished, read the yellow warning the editor gives to you, it tells you to replace length(v) == 0 with isempty(v).

Instead of keeping 'n', you can always delete the first element of v. Also, you need to pass 'odds' as an argument, as you're initializing it as an empty array at each time you call the function (hence the zero output).
The following example seems to do the job:
function result = sumOdd(v,odds)
%sum of odd numbers in a vector v
%sumOdd(v)
if ~isempty(v)
if mod(v(1),2) == 1
odds = [odds;v(1)];
v(1) = [];
sumOdd(v,odds)
elseif mod(v(1),2) == 0
v(1) = [];
sumOdd(v,odds)
end
else
disp(sum(odds))
end
end

Related

How to add random values into an empty vector repeatedly without knowing when it would stop? How to count average number of steps?

Imagine the process of forming a vector v by starting with the empty vector and then repeatedly putting a randomly chosen number from 1 to 20 on the end of v. How could you use Matlab to investigate on average how many steps it takes before v contains all numbers from 1 to 20? You can define/use as many functions or scripts as you want in your answer.
v=[];
v=zeros(1,20);
for a = 1:length(v)
v(a)=randi(20);
end
since v is now only a 1x20 vector, if there are two numbers equal, it definitely
does not have all 20 numbers from 1 to 20
for i = 1:length(v)
for j = i+1:length(v)
if v(i)==v(j)
v=[v randi(20)];
i=i+1;
break;
end
end
end
for k = 1:length(v)
for n = 1:20
if v(k)==n
v=v;
elseif v(k)~=n
a=randi(20);
v=[v a];
end
if a~=n
v=[v randi(20)];
k=k+1;
break;
end
end
end
disp('number of steps: ')
i*k
First of all, the loop generating the vector must be infinite. You can break out of the loop if your condition is met. This is how you can count how many steps you need. You cannot use a loop over 20 steps if you know you'll need more than that. I like using while true and break.
Next, your method of determining if all elements are present is a method of O(n2). This can be done in O(n log n) sorting the elements. This is what unique does. It works by sorting, which, in the general case, is O(n log n) (think QuickSort). So, drawing n elements and after each checking to see if you've got them all is an operation O(n2 log n). This is expensive!
But we're talking about a finite set of integers here. Integers can be sorted in O(n) (look up histogram sort or radix sort). But we can do even better, because we don't even need to physically create the vector or sort its values. We can instead simply keep track of the elements we have seen in an array of length 20: In the loop, generate the next vector element, set the corresponding value in your 20-element array, and when all elements of this array are set, you have seen all values at least once. This is when you break.
My implementation of these two methods is below. The unique method takes 11s to do 10,000 repetitions of this process, and the other one only 0.37s. After 10,000 repetitions, I saw that you need about 72 steps on average to see all 20 integers.
function test
k = 10000;
tic;
n1 = 0;
for ii=1:k
n1 = n1 + method1;
end
n1 = n1 / k;
toc
disp(n1)
tic;
n2 = 0;
for ii=1:k
n2 = n2 + method2;
end
n2 = n2 / k;
toc
disp(n2)
end
function n = method1
k = 20;
v = [];
n = 1;
while true
v(end+1) = randi(k);
if numel(unique(v))==k
break;
end
n = n + 1;
end
end
function n = method2
k = 20;
h = zeros(20,1);
n = 1;
while true
h(randi(k)) = 1;
if all(h)
break;
end
n = n + 1;
end
end
Note on the timings: I use tic/toc here, but it is usually better to use timeit instead. The time difference is large enough for this to not matter all that much. But do make sure that the code that uses tic/toc is inside a function, and not copy-pasted to the command line. Timings are not representative when using tic/toc on the command line because the JIT compiler will not be used.
I'm not sure if I understand your question correctly, but maybe have a look at the unique() function.
if
length(unique(v)) == 20
then you have all values from 1:20 in your vector
v = []
counter = 0;
while length(unique(v)) ~= 20
a = randi(20);
v=[v a];
counter = counter +1
end
the value counter should give you the number of iterations needed until v contains all values.
If you want to get the average amount of iterations by trial and error just make a look around this code and test it 10000 times and average the results form counter.

MATLAB - Check matrix to see if two consecutive numbers = 0

I have a matrix being created in MATLAB but need to check if any two consecutive numbers (by row) = 0 and if it does output with a yes or no without showing the answers. Ive put my code below my final loop is returning errors and im not too sure how to go about this.
%%Input positive integer
n=input('Give a positive integer greater than 1: ');
%%Error for below 1
if n<=1
error('The value given is less than or equal to 1')
end
%%loop for vector v
for i=1:n
v(i)=2^i*3;
end
%display vector
v
A=randi([-5,5],n,n);
A
x = 1;
consecutive = false;
for i = 1:25
if (A(x) + A(x+1) = 0);
consecutive = true;
end
end
There's a lot wrong with the code of your final loop:
You set x to 1 and use it as an index into A, but never change it from 1.
As Amit points out, you are using = (used for assignment) when you should be using == (the equality operator).
As Gondrian points out, you are testing if a sum is equal to zero, but from your description it sounds like you should be testing if each value is zero.
Your loop iterates 25 times (i = 1:25), but it's not clear why, since your matrix A is of size n-by-n.
Instead of using a for loop, it's possible to do this with indexing instead. Since you are checking for consecutive zeroes by row, this is what it would look like:
zeroPairs = (A(:, 1:(n-1)) == 0) & (A(:, 2:n) == 0);
consecutive = any(zeroPairs(:));
The term A(:, 1:(n-1)) gets all of the "left" values in each pairwise comparison and the term A(:, 2:n) gets all of the "right" value. These are compared to 0, then combined. This creates an n-by-(n-1) matrix zeroPairs where a value of true indicates where a pair of consecutive zeroes occurs. This matrix is reshaped into a column vector and any is used to check if a value of true is present anywhere.
You will need to change your if block as follows.
if (A(x) + A(x+1) == 0);
consecutive = true;
end
Notice the == instead of just =. The first one is for comparison and the second one is for assignment. This will get rid of the error that you are currently getting. There may be other issues in the algorithm of your code but I did not examine or try to fix that.
btw:
'if any two consecutive numbers (by row) = 0'
If I understand you right, you should try 'if A(x) == 0 && A(x+1) == 0';
because '(A(x) + A(x+1) == 0)' would be true for -5 and 5, as it equals to 0. But -5 and 5 are not two consecutive zeros.
(or even look at the 'diff' function. It will return a 0 if two following numbers are the same)
To show a vectorized, more Matlab-like approach:
v = 0; % sought value
C = 2; % desired number of consecutive values in a row
consecutive = nnz(conv2(double(A==v), ones(1,C))==C)>0;
This compares each entry of A with the value v, and then applies 2D convolution with a row vector of C ones. Any C horizontally-consecutive entries of A with value v will produce an entry equal to C in the convolution result. So we check if the number of such entries is positive.

How can I simplify this MatLab code?

I would like to know if there is a way to get rid of the inner for loop
for i = 1:size(VALUES)
for k = 2:bins+1
if VALUES(i) < Arr(k)
answer_list(i) = find(Arr == Arr(k)) - 1;
break
end
end
end
VALUES is a file with 100 doubles from 2 to 4
Arr is an array with 4 values, starting at VALUES min a step of 1 and ends at VALUES max
bins is Arr's length - 1
and answer_list is a column of numbers VALUES long that hold the discrete value depending on the size of the bins variable.
I think this is what you look for (in comments are the references to the original lines in your code):
out = bsxfun(#lt,VALUES(:).',Arr(:)) % if VALUES(i) < Arr(k):
out2 = size(out,1)-cumsum(out,1); % find(Arr == Arr(k)) - 1;
answer_list = out2(end,any(out,1)).';
This replaces the whole code, not only the inner loop.

Can operations on submatrices (and subvectors) be vectorized?

I'm currently working on an edge detector in octave. Coming from other programming languages like Java and Python, I'm used to iterating in for loops, rather than performing operations on entire matrices. Now in octave, this causes a serious performance hit, and I'm having a bit of difficulty figuring out how to vectorize my code. I have the following two pieces of code:
1)
function zc = ZeroCrossings(img, T=0.9257)
zc = zeros(size(img));
# Iterate over central positions of all 3x3 submatrices
for y = 2:rows(img) - 1
for x = 2:columns(img) - 1
ndiff = 0;
# Check all necessary pairs of elements of the submatrix (W/E, N/S, NW/SE, NE/SW)
for d = [1, 0; 0, 1; 1, 1; 1, -1]'
p1 = img(y-d(2), x-d(1));
p2 = img(y+d(2), x+d(1));
if sign(p1) != sign(p2) && abs(p1 - p2) >= T
ndiff++;
end
end
# If at least two pairs fit the requirements, these coordinates are a zero crossing
if ndiff >= 2
zc(y, x) = 1;
end
end
end
end
2)
function g = LinkGaps(img, k=5)
g = zeros(size(img));
for i = 1:rows(img)
g(i, :) = link(img(i, :), k);
end
end
function row = link(row, k)
# Find first 1
i = 1;
while i <= length(row) && row(i) == 0
i++;
end
# Iterate over gaps
while true
# Determine gap start
while i <= length(row) && row(i) == 1
i++;
end
start = i;
# Determine gap stop
while i <= length(row) && row(i) == 0
i++;
end
# If stop wasn't reached, exit loop
if i > length(row)
break
end
# If gap is short enough, fill it with 1s
if i - start <= k
row(start:i-1) = 1;
end
end
end
Both of these functions iterate over submatrices (or rows and subrows in the second case), and particularly the first one seems to be slowing down my program quite a bit.
This function takes a matrix of pixels (img) and returns a binary (0/1) matrix, with 1s where zero crossings (pixels whose corresponding 3x3 neighbourhoods fit certain requirements) were found.
The outer 2 for loops seem like they should be possible to vectorize somehow. I can put the body into its own function (taking as an argument the necessary submatrix) but I can't figure out how to then call this function on all submatrices, setting their corresponding (central) positions to the returned value.
Bonus points if the inner for loop can also be vectorized.
This function takes in the binary matrix from the previous one's output, and fills in gaps in its rows (i.e. sets them to 1). A gap is defined as a series of 0s of length <= k, bounded on both sides by 1s.
Now I'm sure at least the outer loop (the one in LinkGaps) is vectorizable. However, the while loop in link again operates on subvectors, rather than single elements so I'm not sure how I'd go about vectorizing it.
Not a full solution, but here is an idea how you could do the first without any loops:
% W/E
I1 = I(2:end-1,1:end-2);
I2 = I(2:end-1,3:end );
C = (I1 .* I2 < 0) .* (abs(I1 - I2)>=T);
% N/S
I1 = I(1:end-2,2:end-1);
I2 = I(3:end, 2:end-1);
C = C + (I1 .* I2 < 0) .* (abs(I1 - I2)>=T);
% proceed similarly with NW/SE and NE/SW
% ...
% zero-crossings where count is at least 2
ZC = C>=2;
Idea: form two subimages that are appropriately shifted, check for the difference in sign (product negative) and threshold the difference. Both tests return a logical (0/1) matrix, the element-wise product does the logical and, result is a 0/1 matrix with 1 where both tests have succeeded. These matrices can be added to keep track of the counts (ndiff).

Print integers in a Matrix coming in order without duplicates

I have several matrices <1x1000> containing integers such as:
matrix = [0,0,0,0,0,30,30,30,40,40,50,50,50,40,0,0,0,30,30,30]
I want to print (disp, and later plot) them like this: 30,40,50,40,30. Basically ignore the duplicates if they come after each other.
Another example:
matrix = [0,0,0,0,10,10,10,10,50,50,50,50,10,10,10,50,50] shall give: 10,50,10,50
Help is very much appreciated!
Use this:
[~,c]=find([NaN diff(matrix)]);
output=matrix(c);
output = output(output~=0)
and to plot the output, simply use: plot(output)
Result = 0;
% loop over all nonzero values in matrix
for Element = matrix
if Element == Result(end)
% skip if equal
continue
else
% add new value
Result(end+1) = Element;
end
end
% discard zero entries
Result = Result(Result ~= 0);
All solutions provided so far use either loops or the function find which are both inefficient.
Just use matrix indexation:
[matrix((matrix(1:end-1)-matrix(2:end))~=0), matrix(end)]
ans =
0 30 40 50 40 0 30
By the way in your example are you discarting the 0s even if they come in repeated sequences?
Lets call the output matrix um then
um(1) = matrix(1);
j = 1;
for i=2: length(matrix)
% Ignore repeating numbers
if (um(j) ~= matrix(i))
j = j + 1;
um(j) = matrix(i);
end
end
% Remove zeros
um = um(um~=0);