Write a recursive function to find the smallest element in a vector(MATLAB) - matlab

Write a recursive function to find the smallest element in a vector.
We can not use loops but can use if statements.
Using RECURSION is a must.
I Could Not think of any solution, the main problem was if I define a function then I have to give it some value and if I do so then whenever recursion occur it will again reset the value of that variable.

function miminimumis=minimumval(k)
aa=k(1);
k=k(k<k(1));
if length(k)==0
miminimumis=aa;
else
% this line gives the recursion
miminimumis=minimumval(k);
end
end
here we create a new array which consists of elements only smaller than the first element. if this array is empty then it means that first element is min, if not we do the same for the new array unless we reach an empty array. the recursion is provided by using the same function in the definition of the function.

Solutions which in the worst case reduce the problem size by 1 will cause the recursive stack to have O(length(array)) growth. An example of this would be when you filter the array to yield values less than the first element when the array is in descending order. This will inevitably lead to stack overflow for sufficiently large arrays. To avoid this, you want to use a recursion which splits the problem of size n into two subproblems of size n/2, yielding O(log(length(array))).
I'm not a Matlab user/programmer, so I'll express the algorithm in pseudo-code. The following assumes that arrays are 1-based and that there is a built-in function min(a,b) which yields the minimum of two scalars, a and b. (If not, it's easy to replace min() with if/else logic.)
function min_element(ary) {
if length(ary) == 1 {
return ary[1]
}
split ary into first_half, second_half which differ in length by no more than 1
return min( min_element(first_half), min_element(second_half) )
}
This could alternatively be written using two additional arguments for the lo_index and hi_index to search between. Calculate the midpoint as the integer average of the low and high indices, and make the two recursive calls min_element(ary, lo_index, mid) and min_element(ary, mid+1, hi_index). The base condition is when lo_index == hi_index, in which case you return that element. This should be faster, since it uses simple integer arithmetic and avoids creating sub-arrays for the subproblems. It has the trade-off of being slightly less friendly to the end user, who has to start the process by calling min_element(ary, 1, length(ary)).
If the stack limit is 500, you'll be limited to arrays of length < 500 using linear stack growth algorithms. With the divide-and-conquer algorithm described above, you won't get stack overflow unless you have an array of length ~2500, much bigger than any array you could actually create.

Related

Unexpected matlab behaviour when using vectorised assignment

I've come across some unexpected behaviour in matlab that I can't make sense of when performing vectorised assignment:
>> q=4;
>> q(q==[1,3,4,5,7,8])
The logical indices contain a true value outside of the array bounds.
>> q(q==[1,3,4,5,7,8])=1
q =
4 0 1
Why does the command q(q==[1,3,4,5,7,8]) result in an error, but the command q(q==[1,3,4,5,7,8])=1 work? And how does it arrive at 4 0 1 being the output?
The difference between q(i) and q(i)=a is that the former must produce the value of an array element; if i is out of bounds, MATLAB chooses to give an error rather than invent a value (good choice IMO). And the latter must write a value to an array element; if i is out of bounds, MATLAB chooses to extend the array so that it is large enough to be able to write to that location (this has also proven to be a good choice, it is useful and used extensively in code). Numeric arrays are extended by adding zeros.
In your specific case, q==[1,3,4,5,7,8] is the logical array [0,0,1,0,0,0]. This means that you are trying to index i=3. Since q has a single value, reading at index 3 is out of bounds, but we can write there. q is padded to size 3 by adding zeros, and then the value 1 is written to the third element.

Image processing, 2D convolution [duplicate]

The following error occurs quite frequently:
Subscript indices must either be real positive integers or logicals
I have found many questions about this but not one with a really generic answer. Hence I would like to have the general solution for dealing with this problem.
Subscript indices must either be real positive integers or logicals
In nearly all cases this error is caused by one of two reasons. Fortunately there is an easy check for this.
First of all make sure you are at the line where the error occurs, this can usually be achieved by using dbstop if error before you run your function or script. Now we can check for the first problem:
1. Somewhere an invalid index is used to access a variable
Find every variable, and see how they are being indexed. A variable being indexed is typically in one of these forms:
variableName(index,index)
variableName{index,index}
variableName{indices}(indices)
Now simply look at the stuff between the brackets, and select every index. Then hit f9 to evaluate the result and check whether it is a real positive integer or logical. Visual inspection is usually sufficient (remember that acceptable values are in true,false or 1,2,3,... BUT NOT 0) , but for a large matrix you can use things like isequal(index, round(index)), or more exactly isequal(x, max(1,round(abs(x)))) to check for real positive integers. To check the class you can use class(index) which should return 'logical' if the values are all 'true' or 'false'.
Make sure to check evaluate every index, even those that look unusual as per the example below. If all indices check out, you are probably facing the second problem:
2. A function name has been overshadowed by a user defined variable
MATLAB functions often have very intuitive names. This is convenient, but sometimes results in accidentally overloading (builtin) functions, i.e. creating a variable with the same name as a function for example you could go max = 9 and for the rest of you script/function Matlab will consider max to be a variable instead of the function max so you will get this error if you try something like max([1 8 0 3 7]) because instead of return the maximum value of that vector, Matlab now assumes you are trying to index the variable max and 0 is an invalid index.
In order to check which variables you have you can look at the workspace. However if you are looking for a systematic approach here is one:
For every letter or word that is followed by brackets () and has not been confirmed to have proper indices in step 1. Check whether it is actually a variable. This can easily be done by using which.
Examples
Simple occurrence of invalid index
a = 1;
b = 2;
c = 3;
a(b/c)
Here we will evaluate b/c and find that it is not a nicely rounded number.
Complicated occurrence of invalid index
a = 1;
b = 2;
c = 3;
d = 1:10;
a(b+mean(d(cell2mat({b}):c)))
I recommend working inside out. So first evaluate the most inner variable being indexed: d. It turns out that cell2mat({b}):c, nicely evaluates to integers. Then evaluate b+mean(d(cell2mat({b}):c)) and find that we don't have an integer or logical as index to a.
Here we will evaluate b/c and find that it is not a nicely rounded number.
Overloaded a function
which mean
% some directory\filename.m
You should see something like this to actually confirm that something is a function.
a = 1:4;
b=0:0.1:1;
mean(a) = 2.5;
mean(b);
Here we see that mean has accidentally been assigned to. Now we get:
which mean
% mean is a variable.
In Matlab (and most other programming languages) the multiplication sign must always be written. While in your math class you probably learned that you can write write a(a+a) instead of a*(a+a), this is not the same in matlab. The first is an indexing or function call, while the second is a multiplication.
>> a=0
a =
0
>> a*(a+a)
ans =
0
>> a(a+a)
Subscript indices must either be real
positive integers or logicals.
Answers to this question so far focused on the sources of this error, which is great. But it is important to understand the powerful yet very intuitive feature of matrix indexing in Matlab. Hence how indexing works and what is a valid index would help avoid this error in the first place by using valid indices.
At its core, given an array A of length n, there are two ways of indexing it.
Linear indexing: with subset of integers from 1 : n (duplicates allowed). 0 is not allowed, as Matlab arrays are 1-based, unless you use the method below. For higher-dimensional arrays, multiple subscripts are internally converted into a linear index, although in an efficient and transparent manner.
Logical indexing:wherein you use a n-length array of 0s and 1s, to pick those elements where indexing is true. In this case, unique(index) must have only 0 and 1.
So a valid indexing array into another array with n number of elements ca be:
entirely logical of the same size, or
linear with subsets of integers from 1:n
Keeping this in mind, invalid indexing error occurs when you mix the two types of indexing: one or more zeros occur in your linearly indexing array, or you mix 0s and 1s with anything other than 0s and 1s :)
There is tons of material online to learn this including this one:
http://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html

Efficient Enumeration of subsets of variable size

There are 2 variables: i and j.
i runs from 1 to fixed constant N. j runs from 1 to M(i), meaning we have an array
M=zeros(N,1);
M=[3,2,5,4];
Also S is a set of say 10 integers. Corresponding to every i, I have to find all possible ways of choosing numbers from S up to a given max limit M(i).
My code:
desired_enumerations={};
for i=1:N
for j=1:M(i)
a = combnk(S,j);
for k=1:size(a,1)
desired_enumerations{end+1,1}=a(k,:);
end
end
end
My question:
I want to pre-compute all possible subsets of S up to max(M) elements outside the double for loop and then use that data inside the for loops so i don't have to enumerate the subsets inside double for loop and avoid repeated calculations.
What is an efficient way to do this?
EDIT:
Just as a bonus if someone could also give the time-complexity of the code in big-O notation. Or i can open a new question.

Sum(X,dim) doesnot work after I load MAT file [duplicate]

The following error occurs quite frequently:
Subscript indices must either be real positive integers or logicals
I have found many questions about this but not one with a really generic answer. Hence I would like to have the general solution for dealing with this problem.
Subscript indices must either be real positive integers or logicals
In nearly all cases this error is caused by one of two reasons. Fortunately there is an easy check for this.
First of all make sure you are at the line where the error occurs, this can usually be achieved by using dbstop if error before you run your function or script. Now we can check for the first problem:
1. Somewhere an invalid index is used to access a variable
Find every variable, and see how they are being indexed. A variable being indexed is typically in one of these forms:
variableName(index,index)
variableName{index,index}
variableName{indices}(indices)
Now simply look at the stuff between the brackets, and select every index. Then hit f9 to evaluate the result and check whether it is a real positive integer or logical. Visual inspection is usually sufficient (remember that acceptable values are in true,false or 1,2,3,... BUT NOT 0) , but for a large matrix you can use things like isequal(index, round(index)), or more exactly isequal(x, max(1,round(abs(x)))) to check for real positive integers. To check the class you can use class(index) which should return 'logical' if the values are all 'true' or 'false'.
Make sure to check evaluate every index, even those that look unusual as per the example below. If all indices check out, you are probably facing the second problem:
2. A function name has been overshadowed by a user defined variable
MATLAB functions often have very intuitive names. This is convenient, but sometimes results in accidentally overloading (builtin) functions, i.e. creating a variable with the same name as a function for example you could go max = 9 and for the rest of you script/function Matlab will consider max to be a variable instead of the function max so you will get this error if you try something like max([1 8 0 3 7]) because instead of return the maximum value of that vector, Matlab now assumes you are trying to index the variable max and 0 is an invalid index.
In order to check which variables you have you can look at the workspace. However if you are looking for a systematic approach here is one:
For every letter or word that is followed by brackets () and has not been confirmed to have proper indices in step 1. Check whether it is actually a variable. This can easily be done by using which.
Examples
Simple occurrence of invalid index
a = 1;
b = 2;
c = 3;
a(b/c)
Here we will evaluate b/c and find that it is not a nicely rounded number.
Complicated occurrence of invalid index
a = 1;
b = 2;
c = 3;
d = 1:10;
a(b+mean(d(cell2mat({b}):c)))
I recommend working inside out. So first evaluate the most inner variable being indexed: d. It turns out that cell2mat({b}):c, nicely evaluates to integers. Then evaluate b+mean(d(cell2mat({b}):c)) and find that we don't have an integer or logical as index to a.
Here we will evaluate b/c and find that it is not a nicely rounded number.
Overloaded a function
which mean
% some directory\filename.m
You should see something like this to actually confirm that something is a function.
a = 1:4;
b=0:0.1:1;
mean(a) = 2.5;
mean(b);
Here we see that mean has accidentally been assigned to. Now we get:
which mean
% mean is a variable.
In Matlab (and most other programming languages) the multiplication sign must always be written. While in your math class you probably learned that you can write write a(a+a) instead of a*(a+a), this is not the same in matlab. The first is an indexing or function call, while the second is a multiplication.
>> a=0
a =
0
>> a*(a+a)
ans =
0
>> a(a+a)
Subscript indices must either be real
positive integers or logicals.
Answers to this question so far focused on the sources of this error, which is great. But it is important to understand the powerful yet very intuitive feature of matrix indexing in Matlab. Hence how indexing works and what is a valid index would help avoid this error in the first place by using valid indices.
At its core, given an array A of length n, there are two ways of indexing it.
Linear indexing: with subset of integers from 1 : n (duplicates allowed). 0 is not allowed, as Matlab arrays are 1-based, unless you use the method below. For higher-dimensional arrays, multiple subscripts are internally converted into a linear index, although in an efficient and transparent manner.
Logical indexing:wherein you use a n-length array of 0s and 1s, to pick those elements where indexing is true. In this case, unique(index) must have only 0 and 1.
So a valid indexing array into another array with n number of elements ca be:
entirely logical of the same size, or
linear with subsets of integers from 1:n
Keeping this in mind, invalid indexing error occurs when you mix the two types of indexing: one or more zeros occur in your linearly indexing array, or you mix 0s and 1s with anything other than 0s and 1s :)
There is tons of material online to learn this including this one:
http://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html

Sum() matlab function [duplicate]

The following error occurs quite frequently:
Subscript indices must either be real positive integers or logicals
I have found many questions about this but not one with a really generic answer. Hence I would like to have the general solution for dealing with this problem.
Subscript indices must either be real positive integers or logicals
In nearly all cases this error is caused by one of two reasons. Fortunately there is an easy check for this.
First of all make sure you are at the line where the error occurs, this can usually be achieved by using dbstop if error before you run your function or script. Now we can check for the first problem:
1. Somewhere an invalid index is used to access a variable
Find every variable, and see how they are being indexed. A variable being indexed is typically in one of these forms:
variableName(index,index)
variableName{index,index}
variableName{indices}(indices)
Now simply look at the stuff between the brackets, and select every index. Then hit f9 to evaluate the result and check whether it is a real positive integer or logical. Visual inspection is usually sufficient (remember that acceptable values are in true,false or 1,2,3,... BUT NOT 0) , but for a large matrix you can use things like isequal(index, round(index)), or more exactly isequal(x, max(1,round(abs(x)))) to check for real positive integers. To check the class you can use class(index) which should return 'logical' if the values are all 'true' or 'false'.
Make sure to check evaluate every index, even those that look unusual as per the example below. If all indices check out, you are probably facing the second problem:
2. A function name has been overshadowed by a user defined variable
MATLAB functions often have very intuitive names. This is convenient, but sometimes results in accidentally overloading (builtin) functions, i.e. creating a variable with the same name as a function for example you could go max = 9 and for the rest of you script/function Matlab will consider max to be a variable instead of the function max so you will get this error if you try something like max([1 8 0 3 7]) because instead of return the maximum value of that vector, Matlab now assumes you are trying to index the variable max and 0 is an invalid index.
In order to check which variables you have you can look at the workspace. However if you are looking for a systematic approach here is one:
For every letter or word that is followed by brackets () and has not been confirmed to have proper indices in step 1. Check whether it is actually a variable. This can easily be done by using which.
Examples
Simple occurrence of invalid index
a = 1;
b = 2;
c = 3;
a(b/c)
Here we will evaluate b/c and find that it is not a nicely rounded number.
Complicated occurrence of invalid index
a = 1;
b = 2;
c = 3;
d = 1:10;
a(b+mean(d(cell2mat({b}):c)))
I recommend working inside out. So first evaluate the most inner variable being indexed: d. It turns out that cell2mat({b}):c, nicely evaluates to integers. Then evaluate b+mean(d(cell2mat({b}):c)) and find that we don't have an integer or logical as index to a.
Here we will evaluate b/c and find that it is not a nicely rounded number.
Overloaded a function
which mean
% some directory\filename.m
You should see something like this to actually confirm that something is a function.
a = 1:4;
b=0:0.1:1;
mean(a) = 2.5;
mean(b);
Here we see that mean has accidentally been assigned to. Now we get:
which mean
% mean is a variable.
In Matlab (and most other programming languages) the multiplication sign must always be written. While in your math class you probably learned that you can write write a(a+a) instead of a*(a+a), this is not the same in matlab. The first is an indexing or function call, while the second is a multiplication.
>> a=0
a =
0
>> a*(a+a)
ans =
0
>> a(a+a)
Subscript indices must either be real
positive integers or logicals.
Answers to this question so far focused on the sources of this error, which is great. But it is important to understand the powerful yet very intuitive feature of matrix indexing in Matlab. Hence how indexing works and what is a valid index would help avoid this error in the first place by using valid indices.
At its core, given an array A of length n, there are two ways of indexing it.
Linear indexing: with subset of integers from 1 : n (duplicates allowed). 0 is not allowed, as Matlab arrays are 1-based, unless you use the method below. For higher-dimensional arrays, multiple subscripts are internally converted into a linear index, although in an efficient and transparent manner.
Logical indexing:wherein you use a n-length array of 0s and 1s, to pick those elements where indexing is true. In this case, unique(index) must have only 0 and 1.
So a valid indexing array into another array with n number of elements ca be:
entirely logical of the same size, or
linear with subsets of integers from 1:n
Keeping this in mind, invalid indexing error occurs when you mix the two types of indexing: one or more zeros occur in your linearly indexing array, or you mix 0s and 1s with anything other than 0s and 1s :)
There is tons of material online to learn this including this one:
http://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html