2
q=
 2
 4
 6
 1
 6
 8

From=
 1
 4
 2

To=
 3
 6
 3

q is a sequence of points. For instance, q(From(1):To(1)) gives 2,4,6. I want to vectorize this example.

This is non-vectorized working code:

J=3;
L=cell(J,1);
for j=1:J
    L{j}=q(From(j):To(j));
end

Its result is:

L=
 2,4,6   % j=1
 1,6,8   % j=2
 4,6     % j=3

I cannot figure out how to get a vectorized form of this code. I tried to convert L into 2-dim array, but anyway nothing works.

1
  • have you tried with arrayfun? Commented Dec 19, 2015 at 14:44

1 Answer 1

1

You can get rid of the for loop by using arrayfun to apply a specific function on all elements of the inputs. However, I'm not sure if it will be much faster than the loopy version.

The code below produces output equivalent to your original cell array L:

L2 = arrayfun(@(x,y)q(x:y), From, To, 'UniformOutput', false);

Here, @(x,y)q(x:y) defines an anonymous function that returns subvectors from q according to the inputs x and y, which are picked by arrayfun from your input vectors From and To.


As suggested in the comments, if you desire extra genericity you can specify another function handle like this:

L_fun = @(q)arrayfun(@(x,y)q(x:y), From, To, 'uniformoutput', false);

...and then call it for an arbitrary vector (not necessarily your original q) as such:

q2 = rand(10,1); %// Random vector for testing
Lout = L_fun(q2); %// Use From and To to pick from q2

Or even define a handle which takes all inputs:

L_fun = @(q,From,To)arrayfun(@(x,y)q(x:y), From, To, 'uniformoutput', false);

but in this case it might be better to actually write a named function already.

Sign up to request clarification or add additional context in comments.

4 Comments

OP may want to put q as an argument of the handle function in order to reuse the code on the more easy way. Nice answer thought :)
@HamtaroWarrior: What do you mean? @(q(x:y)) ?
I believe I understood what @HamtaroWarrior means. I updated my answer. It's possible, but I feel if you get very generic it might be worth it to just write a named function to do it instead of applying a handle :)
Nah, I thought about this kind on generalizations : arrayfun(@(q,From,To) q(From:To), q, From, To, 'UniformOutput',0) But your idea is also great. Anyway it is not really important :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.