Hi,
I have a 5 x 1 array, a = [ 0 1 0 2 0]. (this is a generalization of a larger problem)
I want create and index that fills all the values starting with 1, and ending at the last occurance of the number 2 (that does not have another 1 in between)?
I want to create b = [0 1 1 1 0].
I can do:
b = zeros(1,length(a))
b(strfind(a, [1]):strfind(a, [2])) = 1
That works for that specific case.
But, what if I have a = [ 0 1 0 2 0 2 1]? I want to create b = [0 1 1 1 1 1 0].
Any help woudl be appreciated! Thanks!
Inna

 Réponse acceptée

per isakson
per isakson le 20 Oct 2020

0 votes

Study this
%%
a = [0,1,0,2,0,2,1];
ixb = find( a==1, 1,'first'); % begin
ixe = find( a==2, 1,'last'); % end
%%
b = zeros(size(a));
b(ixb:ixe)=1;
b contains the result
>> b
b =
0 1 1 1 1 1 0

3 commentaires

Inna Pelloso
Inna Pelloso le 20 Oct 2020
Modifié(e) : per isakson le 21 Oct 2020
Thank you, I didn't know about the 'first' and 'last' option.
What if I have multiple such sequances within a, and want to index them? For example,
a = [0,1,0,2,0,2,1,0,1,0, 2 ],
and I want
b = [0, 1, 1, 1, 1, 1, 0, 1, 1,1]
per isakson
per isakson le 21 Oct 2020
Modifié(e) : per isakson le 21 Oct 2020
"the 'first' and 'last'" using Matlab includes a lot of searching and reading of the documentation.
%%
a = [0,1,0,2,0,2,1,0,1,0,2];
chr = sprintf('%d',a);
[ix1,ix2] = regexp( chr, '1[^1]+2', 'start', 'end' );
%%
b = zeros(size(a));
for jj = 1 : numel(ix1)
b(ix1(jj):ix2(jj)) = 1;
end
and inspect b
>> b
b =
0 1 1 1 1 1 0 0 1 1 1
^
I think there is a mistake in your value of b ; a missing zero.
regexp() requires more than searching and reading the documentation.

Connectez-vous pour commenter.

Plus de réponses (1)

Inna Pelloso
Inna Pelloso le 21 Oct 2020

0 votes

Thank you! Really appreciate it.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Produits

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by