Problem 1042. Operate on matrices of unequal, yet similar, size
You may want to add a vector to a matrix, implying that the vector is added to each column of the matrix. Or multiply a 3x4x5 matrix with a 3x4 matrix, intending to do that for every element in the 3th dimension.
>> [1 2;3 4].*[1 2]
ans =
1 4 3 8
It's clear what you want to do, but Matlab is very strict and gives an error, unless you first make the size of the arguments match.
You will now create a function that operates on two arguments, performing one of the operations 'plus', 'minus', 'times', 'power', 'ldivide' or 'rdivide' (specified as the 3rd argument), after it has matched the sizes of first two input arguments.
It should work on input arguments of more than two dimensions, of arguments of different dimensions, as long as they are numerical matrices, vectors, or values.
There is one limitation: for dimensions in which the size of the input arguments differ, the size of one of them should be one.
Note: Solutions wrapped in eval(c), inline, str2func, regexprep (dynamic regular expressions), etc, are not appreciated.
Solution Stats
Problem Comments
-
3 Comments
I don't see the point of outlawing feval.
The question is not clear at all! What is that the poster wants us to do?
The assignment is to "... create a function that operates on two arguments, performing one of the operations 'plus', 'minus', 'times', 'power', 'ldivide' or 'rdivide' (specified as the 3rd argument), after it has matched the sizes of first two input arguments."
So you have to make a functions that performs one of the basic math operations on two input arguments, and which operation it should be is determined by the 3rd input argument.
You are lucky that nowadays Matlab itself tries to match the size of the input arguments of those operations. So if you add a scalar to a vector, the program is that smart that it uses the scalar term for all vector terms. And when the 1st argument is a column vector, it is used for all columns of matrix when the 2nd argument is a matrix that has an equal number of rows as the column has.
When this 'problem' was created, Matlab did not do that by itself, and you had to take care of that yourself.
So the problem is is even easier than you may think. See 'help ops' for basic math in Matlab.
Solution Comments
Show commentsProblem Recent Solvers190
Suggested Problems
-
1758 Solvers
-
10072 Solvers
-
4970 Solvers
-
Mersenne Primes vs. All Primes
592 Solvers
-
7870 Solvers
More from this Author31
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!