What's the correct syntax for applying a function to sub elements of a matrix without using a loop?

StackOverflow https://stackoverflow.com/questions/2239022

  •  19-09-2019
  •  | 
  •  

Question

I have a defined a function (GetDepth) which does something fairly trivial, eg takes in a 2x4 matrix and outputs a 2x1 matrix. I then have an 2x4xn matrix I want to apply it to, and I'm expecting an 2x1xn matrix result.

What is the correct syntax to apply my function to the matrix without resorting to using a loop?

ed. As requested, here's an example of the thing I'm trying to do:

function [bidWSize, askWSize] = getWSizes(m, bookSizeHistory)
    bidWSize = sum(bookSizeHistory(2:4, 1, m));
    askWSize = sum(bookSizeHistory(2:4, 2, m));
end

Currently I'm then looping and feeding into a 2x1xn output

Was it helpful?

Solution

You'll have to write the function so that it can handle matrices of nx2x4. If indeed it does something trivial, it shouldn't be too difficult. If you have any trouble with that, you can post it here and ask for help.

EDIT:

sum is a function that works well with matrices, so you can achieve what you want by just summing over the matrix, and playing with dimensions. you don't need the function at all:

sum(bookSizeHistory(2:4, 1:2, :))

sums over the 1st dimension (like what you do in the function), so assuming bookSizeHistory's size is Kx2xN, the output of this sum is 1x2xN. you can add a permute to rearrange the dimensions as you wish:

permute(sum(bookSizeHistory(2:4, 1:2, :)), [2 1 3])

should give you what you need.

OTHER TIPS

You can perform functions on individual elements by using the "." operator. For example, bringing each element to some power, you would use:

C=A.^B;

Instead of:

[rows,cols]=size(A);
for i=1:rows
    for j=1:cols
        C=A(i,j)^B;
    end
end

This gives much shorter code than a loop with the same results. It's usually referred to as "vectorized" code, which takes advantage of BLAS functions. Otherwise Matlab is more like an interpreted language, which is far slower. Other functions perform operations on all rows or columns in an array. If A were a 2-D array (2,4), sum(A) would give the sum of each column. Where the total sum could be found a few different ways:

A_temp=reshape(A,[1,8]);
B=sum(A_temp);

or

A=sum(sum(A));

There may be some other functionality in the sum command that allows this to be done with a single calling with some extra argument, but this is still a decently fast way to do it.

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