Question

Trying to find a way to call the exponentiation function ( ^ ) used in a custom function for every item in a matrix in GNU Octave.

I am quite a beginner, and I suppose that this is very simple, but I can't get it to work.


The code looks like this:

function result = the_function(the_val)
    result = (the_val - 5) ^ 2
endfunction


I have tried to call it like this:

>> A = [1,2,3];
>> the_function(A);
>> arrayfun(@the_function, A);
>> A .@the_function 2;

None of these have worked (the last one I believe is simply not correct syntax), throwing the error:

error: for A^b, A must be a square matrix

This, I guess, means it is trying to square the matrix, not the elements inside of it.

How should I do this?

Thanks very much!

Was it helpful?

Solution

It is correct to call the function as the_function(A), but you have to make sure the function can handle a vector input. As you say, (the_val - 5)^2 tries to square the matrix (and it thus gives an error if the_val is not square). To compute an element-wise power you use .^ instead of ^.

So: in the definition of your function, you need to change

result = (the_val-5)^2;

to

result = (the_val-5).^2;

As an additional note, since your code as it stands does work with scalar inputs, you could also use the arrayfun approach. The correct syntax would be (remove the @):

arrayfun(the_function, A)

However, using arrayfun is usually slower than defining your function such that it works directly with vector inputs (or "vectorizing" it). So, whenever possible, vectorize your function. That's what my .^suggestion above does.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top