Indexing portions of a vector with array

3 visualizaciones (últimos 30 días)
Mohammed Kagalwala
Mohammed Kagalwala el 10 de Dic. de 2019
Comentada: Jeremy el 10 de Dic. de 2019
Hi,
I currently have a vector a that is 12 x1. I want to index it such that I get the following vector q = [a(4:7),a(4:7)]. I can create an array [4 4] and [7 7], when I try to index a([4 4], [7 7]). I only get q = a(4:7). Can someone help me with the correct syntax here? Is this even possible with this sort of indexing ?
Sample input:
a = [1 2 3 4 5 6 7 8 9 10 11 12];
Sample output:
q = [a(4:7),a(4:7)] = [4 5 6 7 4 5 6 7]
The size of a can vary and the index 4:7 can vary
Thank you.
  4 comentarios
Jeremy
Jeremy el 10 de Dic. de 2019
What exactly is the problem? The code you provided appears to do what you are asking for
Mohammed Kagalwala
Mohammed Kagalwala el 10 de Dic. de 2019
Editada: Mohammed Kagalwala el 10 de Dic. de 2019
I want to perform this action in general where all I'm given is an array of start indecies and an array of stop indecies. In the example, provided above this would [4 4], [7 7]. This could be of size N. I want to create q using these two arrays, WITHOUT using for loops.

Iniciar sesión para comentar.

Respuestas (1)

Jeremy
Jeremy el 10 de Dic. de 2019
Editada: Jeremy el 10 de Dic. de 2019
I had to think about this for a while, but I think that this accomplishes the task you are looking for
a = 1:12;
id_start = [4 4]';
id_stop = [7 7]';
c = arrayfun(@colon,id_start,id_stop,'UniformOutput',false);
d = cell2mat(c);
p = reshape(d',[1 numel(d)]);
q = a(p);
  2 comentarios
Mohammed Kagalwala
Mohammed Kagalwala el 10 de Dic. de 2019
Thanks ! Works just as I described. Though I did a timing test against a for-loop which showed the for-loop was the faster method. I'm curious if there's a way to beat a for-loops speed.
Jeremy
Jeremy el 10 de Dic. de 2019
I think arrayfun is, in general, not great if you are looking to optimize efficiency. But you asked for no loops and I wanted to solve the puzzle - I wasn't able to get the colon operator to work on the array of start and stop indices without it. Maybe there is another way...

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by