I am trying to produce something like this in MATLAB with function handle
f=#(x,y)(x(1)*x(2)+y);
c=[2 3 4;5 9 2];
h=[5 1 2];
f(c,h)
The answer should be:
15 11 12
But when I write this code below, it just builds a number not an array.
f=#(x)(x(1)*x(2))
f(c)
answer:
10
Can someone explain me where I went wrong?
I do not know what you expected here. The cause of the problem is quite clear.
a = 1;
b = 2;
c = [3 4];
d = a*b+c;
is a scalar + vector operation which always returns
ans = [a*b+c(1), a*b+c(2)];
however scalar*scalar which was the second case always returns a scalar. What you do is that you multiply the first matrix element of x (or c) with the second element. That is to say element c(1,1)*c(2,1) since matlab works columnwise. If you looks at your values you would probably notice the answer is incorrect as well, if you are trying to do what I think you are. You could try this instead,
f=#(x,y)(x(1,:).*x(2,:)+y);
c=[2 3 4;5 9 2];
h=[5 1 2];
f(c,h)
which multipies the elements on the first row of x with the same column on the second row and then adds y. An anonymous function takes a number of inputs and perform a defined operation, the same as ordinary functions or ordinary codes. You can see them as functions that does not require a call to another m file. The main differences (except that ordinary functions gives more freedom), are how they are handled by matlab and not in the syntax.
Related
Image of problem
They lost me at the part where " = -1"
This is my understanding of the solution(so far).
They took the arr variable and scanned for elements that have a remainder of 1 when divided by 2. The = -1 part is where I'm confused.
What are the steps going on in here to replace those odd numbers as
negative 1?
Could someone explain in more depth how "arr[arr % 2 == 1]"
works? I think I have a very simple understanding of it.
Also, what is this particular technique called?
EDIT:
So I tried the solution they gave and it doesn't even run...Not sure if I did something wrong on my end.
Original site link: Source
Just like anything else you're trying to understand, take it step by step. Try printing out each of these intermediate expressions:
arr is a numpy array. This is important, because all of these steps depend on special numpy features - they wouldn't work on an ordinary list.
arr % 2 is an array of the same size, containing the parity of each of the original numbers - 0 for even, 1 for odd.
arr % 2 == 1 turns that into an array of booleans - False for even, True for odd.
arr[arr % 2 == 1] invokes numpy's special boolean indexing feature - it gives you a view of a (possibly discontiguous) subset of the array, wherever the index value was True. In this case, the view contains only the odd numbers of the original array.
arr[arr % 2 == 1] = -1 assigns the same value to each element in the view, overwriting all of the original odd numbers.
A key numpy concept used in all of the steps is "broadcasting" - basically, whenever an operation is attempted between an array and a single element, the single element is effectively replicated to match the size of the array. So, in arr % 2, the 2 notionally becomes an array of 2s, the same size as arr.
I had an interview and was asked a question that I'd like to understand the solution.
The Question
Create a recursive function that returns the number of possible combinations of arrays of a given length that could be made from an array of non-repeating consecutive integers.
f(array, length) = Combinations
Example 1
array = [0,1,2,3]
length = 2
Combinations = 10 (all combinations: [0,0] [0,1] [0,2] [0,3] [1,1] [1,2] [1,3] [2,2] [2,3] [3,3])
Note that [0,0] is allowed but [1,0] is not because [0,1] is defined
Example 2
array = [0,1]
length = 3
Combinations = 4 (all combinations: [0,0,0] [0,0,1] [0,1,1] [1,1,1])
One "hint" was offered. The interviewer said the array itself shouldn't matter; the length was all that was needed.
This algorithm can be expressed recursively because the solution can be expressed in terms of solutions for smaller inputs. "Smaller" here has two meanings:
A subset of the array; specifically the sub-array after the current element index
Solutions for smaller length; these can be added together to give the solution for length + 1
Stopping conditions:
When the array size A = 1 - only one combination can be generated
When the length L = 1 - number of combinations = number of elements in array
The fully recursive procedure is a surprisingly simple one-liner:
return [recursive call to rest of array, same length] +
[recursive call to same array, length - 1]
This is called dynamic programming.
Code:
int F(int A, int L)
{
if (A <= 1) return 1;
if (L <= 1) return A;
return F(A - 1, L) + F(A, L - 1);
}
Tests:
F(4, 2) = 10
F(2, 3) = 4
F(3, 5) = 21 (trace it with pen-and-paper to see for yourself)
EDIT: I've given an elegant and simple solution, but I perhaps haven't explained it as well as #RoryDaulton. Consider giving his answer credit too.
You do not give a target language and you do not say just how much help you want. So I'll give the overall idea of an algorithm that should be simple to code if you know recursion in a certain language. Ask if you want more code in Python, my current preferred language.
You know you need to do recursion, and you have two things you could recurse on: the length of the given array or the length of the desired arrays. Let's recurse on the second, and let's say the given array is [0, 1, ..., n-1] since you know that the actual contents are irrelevant.
If the desired length r is 1 you know there are only n desired arrays, namely [0], [1], ..., [n-1]. So there is the base case for your recursion.
If you have a "combination" of length r-1, how can that be expanded to length r and keep the requirements? Look at the last element in the array of length r-1--let's call it k. The next element cannot be less than that, so all the possible arrays extended to length r are the r-1 array appended with k', 'k+1, ..., n-1. Those are n-k arrays of length r.
Is it clear how to code that? Note that you do not need to keep all the arrays of length r-1, you only need the count of how many arrays there are that end with the element 0 or 1 or ... n-1. That makes it convenient to code--not much memory is needed. In fact, things can be reduced further--I'll leave that to you.
Note that the interviewer probably did not want the code, he wanted your thought-process leading to the code to see the way you think. This is one way to think the problem through.
The round function can take a scalar and operate on it. However it can also take an array and operate on it in expected manner.
>> round(2.3)
ans =
2
>> round([2.3,3.4])
ans =
2 3
I similarly have a function and want it to work in the ""expected"" manner for array inputs. It works well for scalar inputs. I could run a for loop and evaluate my function on each element of the array but what other smarter ways do i have available?
For further concreteness, i have:
function [a,b]=func(c,d,e,f)
And i have d,e,f but i want to evaluate the function to several values of c:-
g=[];
for i=1:10
[a,b]=func(c(i),d,e,f);
g=[g;[a,b]];
end
I am not fully sure how to apply arrayfun though i believe it is what i should use.
What you are looking for is the arrayfun function.
Here is the documentation: http://www.mathworks.com/help/matlab/ref/arrayfun.html
Say, I have this function:
function res = myTest(a,b)
size(a) % for checking that we work on each element
res = a+1;
res = res +b;
I have a matrix A
A = magic(3);
I want to apply myTest with a equal to each element in A
A1 = arrayfun(#(x) myTest(x,2),A)
(x is replaced by the elements of the array declared after the comma)
find() function returns the indices where the elements are non-zero. I tried with different array sizes but both give error :
In an assignment A(I) = B, the number of elements in B and I must be the same.
I am confused because when the array size is same, still I am getting this error.
This is just to understand what went wrong:
LEt,
Example 1: Same array size
A = [20;21;3;45;5;19;1;8;2;1];
B = A;
for i =1:length(B)
pos(i) = find(A == B(i));
end
I should have got pos = [1,2,3,4,5,6,7,8,9,10]. But the loops exits after i = 7, giving `pos = [1,2,3,4,5,6]'
Example 2: Dissimilar array size
C = [20;1;10;3];
for i =1:length(C)
pos(i) = find(A == C(i));
end
Can somebody please explain what is wrong in my understanding and an illustration of how I can work with same and different array length of A and B? Thank you.
The problem is that find(A == 1) returns two indexes, both 7 and 10, and that can't be stored in pos(i), since pos(i) can only hold a single number.
Unfortunately, the generic error message happened to have the same name for the matrices as two of your matrices, which can be confusing before you'we seen it a few times.
For example, if I want to read the middle value from magic(5), I can do so like this:
M = magic(5);
value = M(3,3);
to get value == 13. I'd like to be able to do something like one of these:
value = magic(5)(3,3);
value = (magic(5))(3,3);
to dispense with the intermediate variable. However, MATLAB complains about Unbalanced or unexpected parenthesis or bracket on the first parenthesis before the 3.
Is it possible to read values from an array/matrix without first assigning it to a variable?
It actually is possible to do what you want, but you have to use the functional form of the indexing operator. When you perform an indexing operation using (), you are actually making a call to the subsref function. So, even though you can't do this:
value = magic(5)(3, 3);
You can do this:
value = subsref(magic(5), struct('type', '()', 'subs', {{3, 3}}));
Ugly, but possible. ;)
In general, you just have to change the indexing step to a function call so you don't have two sets of parentheses immediately following one another. Another way to do this would be to define your own anonymous function to do the subscripted indexing. For example:
subindex = #(A, r, c) A(r, c); % An anonymous function for 2-D indexing
value = subindex(magic(5), 3, 3); % Use the function to index the matrix
However, when all is said and done the temporary local variable solution is much more readable, and definitely what I would suggest.
There was just good blog post on Loren on the Art of Matlab a couple days ago with a couple gems that might help. In particular, using helper functions like:
paren = #(x, varargin) x(varargin{:});
curly = #(x, varargin) x{varargin{:}};
where paren() can be used like
paren(magic(5), 3, 3);
would return
ans = 16
I would also surmise that this will be faster than gnovice's answer, but I haven't checked (Use the profiler!!!). That being said, you also have to include these function definitions somewhere. I personally have made them independent functions in my path, because they are super useful.
These functions and others are now available in the Functional Programming Constructs add-on which is available through the MATLAB Add-On Explorer or on the File Exchange.
How do you feel about using undocumented features:
>> builtin('_paren', magic(5), 3, 3) %# M(3,3)
ans =
13
or for cell arrays:
>> builtin('_brace', num2cell(magic(5)), 3, 3) %# C{3,3}
ans =
13
Just like magic :)
UPDATE:
Bad news, the above hack doesn't work anymore in R2015b! That's fine, it was undocumented functionality and we cannot rely on it as a supported feature :)
For those wondering where to find this type of thing, look in the folder fullfile(matlabroot,'bin','registry'). There's a bunch of XML files there that list all kinds of goodies. Be warned that calling some of these functions directly can easily crash your MATLAB session.
At least in MATLAB 2013a you can use getfield like:
a=rand(5);
getfield(a,{1,2}) % etc
to get the element at (1,2)
unfortunately syntax like magic(5)(3,3) is not supported by matlab. you need to use temporary intermediate variables. you can free up the memory after use, e.g.
tmp = magic(3);
myVar = tmp(3,3);
clear tmp
Note that if you compare running times with the standard way (asign the result and then access entries), they are exactly the same.
subs=#(M,i,j) M(i,j);
>> for nit=1:10;tic;subs(magic(100),1:10,1:10);tlap(nit)=toc;end;mean(tlap)
ans =
0.0103
>> for nit=1:10,tic;M=magic(100); M(1:10,1:10);tlap(nit)=toc;end;mean(tlap)
ans =
0.0101
To my opinion, the bottom line is : MATLAB does not have pointers, you have to live with it.
It could be more simple if you make a new function:
function [ element ] = getElem( matrix, index1, index2 )
element = matrix(index1, index2);
end
and then use it:
value = getElem(magic(5), 3, 3);
Your initial notation is the most concise way to do this:
M = magic(5); %create
value = M(3,3); % extract useful data
clear M; %free memory
If you are doing this in a loop you can just reassign M every time and ignore the clear statement as well.
To complement Amro's answer, you can use feval instead of builtin. There is no difference, really, unless you try to overload the operator function:
BUILTIN(...) is the same as FEVAL(...) except that it will call the
original built-in version of the function even if an overloaded one
exists (for this to work, you must never overload
BUILTIN).
>> feval('_paren', magic(5), 3, 3) % M(3,3)
ans =
13
>> feval('_brace', num2cell(magic(5)), 3, 3) % C{3,3}
ans =
13
What's interesting is that feval seems to be just a tiny bit quicker than builtin (by ~3.5%), at least in Matlab 2013b, which is weird given that feval needs to check if the function is overloaded, unlike builtin:
>> tic; for i=1:1e6, feval('_paren', magic(5), 3, 3); end; toc;
Elapsed time is 49.904117 seconds.
>> tic; for i=1:1e6, builtin('_paren', magic(5), 3, 3); end; toc;
Elapsed time is 51.485339 seconds.