MATLAB Answers

Editing sections of an array that are pointed to by two vectors: one with starting indexes, another with end indexes

1 view (last 30 days)
Ben Anstrom
Ben Anstrom on 25 Dec 2019
Edited: per isakson on 25 Dec 2019
Hello everyone,
I am trying to access sections of an array such as,
data = [5 7 10 10.5 11.5 13 15 16 20.5 24 30];
to create an equal length logical array based off a logical function i wrote.
The logical function should only be applied between the start and end indexes that are saved in the following variables:
indStart = [0 0 1 0 0 0 0 1 0 0 0];
indEnd = [0 0 0 0 1 0 0 0 0 1 0];
alternatively, after running find() i could use:
inStart = [3 7];
indEnd = [5 10];
I have used arrayfun() to get the following output from the written logical function:
result = arrayfun(@(x1,x2)fun(x1, x2) , indStart, indEnd, 'uni', false);
result = { [0 1 0] }
{ [0 1 1 0] }
The problem that i am having is that i want to have this data superimposed onto an array of zeros that has a an equal length to data. Such as:
result = [0 0 0 1 0 0 0 1 1 0 0];
I know i can do this quite easily with a for loop, but i am trying to accomplish this using indexing and logical statements so that processing time stays down. The final script needs to be processed by ga(), so any cut down on processing time is very valuable.
Thank you to anyone who can help!

  2 Comments

David Hill
David Hill on 25 Dec 2019
My understanding is that arrayfun() is the same as a for-loop. What is the logical function you are applying?
dpb
dpb on 25 Dec 2019
David is quite right-- arrayfun is probably going to be slower than a straightforward loop altho it does have it's place.
I'm also having a heckuva time trying to figure out just what it is that you're trying to do, specifically.
Not having the function definition doesn't help...
I think you've tried and maybe I'm just dense but I'd suggest outline a sample input array and then the desired output and how know that's the right input.
It would seem that perhaps combining the two logical position vectors filling in the runs might solve the problem...

Sign in to comment.

Answers (1)

per isakson
per isakson on 25 Dec 2019
Edited: per isakson on 25 Dec 2019
Try
>> isSelected = logical([cumsum(indStart),0]-[0,cumsum(indEnd)]);
>> isSelected(end) = [];
>> data(isSelected)
ans =
10 10.5 11.5 16 20.5 24
where indStart and indEnd are the logical variables

  0 Comments

Sign in to comment.

Sign in to answer this question.