Argyll
Argyll

Reputation: 9875

How to apply a binary function to a cell array and a double array

I have a cell of arrays (e.g. character vectors) that takes positional indexing and a double array containing positing integers that are meant to be array indices. Is there a native function that can apply the indices to the cell of arrays?

For example,

A={'abc','asdfc','aojcdfw','casd'};
B=[3,5,4,1];

Is there a native function that can output the following?

{A{1}(B(1):end), A{2}(B(2):end), A{3}(B(3):end), A{4}(B(4):end)}

Upvotes: 1

Views: 109

Answers (2)

Sardar Usama
Sardar Usama

Reputation: 19689

extractAfter does exactly this.

>> extractAfter(A, B-1)
ans =
  1×4 cell array
    {'c'}    {'c'}    {'cdfw'}    {'casd'}

Upvotes: 3

rinkert
rinkert

Reputation: 6863

You can do it with a cellfun. For cellfun, all inputs must be cells, so I first convert B to cell using num2cell.

cellfun(@(a,b) a(b:end), A, num2cell(B), 'UniformOutput', false);

Upvotes: 1

Related Questions