0

I have data of sample size m of n x n matrices in an n by m*n matrix call it P.

I also have a function, call if f, that operates on a fixed vector, call it v, and n x n matrices and returns a real number.

I want to to create a 1 x m vector of real numbers, call it d, by operating f on v and each of the n x n matrices in P.

So, say for example, n = 3 and m = 6 I would want:

d(1) = f(v,P(:,1:3)), d(2) = f(v,P(:,4:6)), . . ., d(6) = f(v,P(:,16:18)) 

How can I do this without making a loop?

Thanks!

4
  • 1
    If you have data of sample size m of nxn matrices then won't it be m by n*n matrix? Commented Apr 13, 2013 at 1:36
  • What does your function do? Commented Apr 13, 2013 at 1:39
  • 1
    @Parag OP is saying he has m nxn matrices stacked side by size, so the final matrix is nx(m*n) Commented Apr 13, 2013 at 1:48
  • "I have data of sample size m of n x n matrices in an n by m*n matrix call it P" Doesn't make sense to me. Do you have a 3d array P(n,n,m)? If not, I would save it like that and use bsxfun() along the third dimension (if I get the nature of your problem). Commented Apr 13, 2013 at 15:33

1 Answer 1

1

Without knowing what your f function do, I can only suggest pseudo-vectorized solution with ARRAYFUN:

d = arrayfun( @(x) f(v,P(:,x:x+2)), n-2:3:n*m ); 

It run with almost the same speed as a simple loop (which I think has clearer code):

d = zeros(1,m); for k = 1:m d(k) = f(v,P(:,n*k-2:n*k)); end 
Sign up to request clarification or add additional context in comments.

3 Comments

This is the important thing, as you say: "which I think has clearer code". Code that will run at virtually the same speed as a loop, so why create a piece of code that will be impossible to read? Vectorization can run wild at times.
I have used the array solution already but this function has to be evaluated many times for different values of v (it is minimized with respect to v to be exact). So I'm hoping to speed things up, with a large data set (m > 75) and high dimension (n > 3) it can take over an hour to minimize. It shouldn't be an impossible task. The closest I've come (with a suggestion from another forum) is: P=reshape(P,n,n,m); a = 1:m; d = f(v,P(:,:,a)) but to no avail! After I vectorize I hope to evaluate the function in parallel!
If your bottleneck really is that one loop you might have better luck writing it as a MEX function. At a certain point it becomes faster to write something in C than to vectorise it in MATLAB

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.