views:

75

answers:

2

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

+3  A: 

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.

Ofri Raviv
It's doing something to the tune of sum(mat(2:4, 1)), so we really are talking extremely trivial. It just struck me as an odd thing that you can't sensibly compose across a matrix without looping, when the literature stresses vectorisation over looping quite so heavily!
AlecZorab
why dont you post the actual code for this function? if you are computing the sum of a subset of the input matrix, you probably can vectorize the code..
Amro
Most definitely.
Jacob
edited the question with sample code
AlecZorab
edited the answer
Ofri Raviv
+1  A: 

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.

Jeff