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

34.16% Correct | 65.84% Incorrect
Last Solution submitted on Dec 28, 2023

Problem Comments

Solution Comments

Show comments

Problem Recent Solvers184

Suggested Problems

More from this Author31

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!