Array creation with condition from another array

10 visualizzazioni (ultimi 30 giorni)
Hi,
I have an array like that x and I want to verify if two consecutive elements from it are 00,01,10 or 11, and at these conditions I will initialize in another array a single value like in the code:
x = randi([0,1],1,n);%n is input from a text box
for i=1:2:length(x)%i verify from 2 in 2 values from array
if(x(i)==0 && x(i+1)==0)
y(i)=1;
elseif(x(i)==0 && x(i+1)==1)
y(i)=3;%and so on for 10,11
end
end
The problem is that how can I minimize the size of y array because in this way, the program assigns me 1 for y(0) and for y(1) the value from x(1). I want in a way to delete x(1) in order to remain only values from y(0),y(2),... and so on.

Risposta accettata

Asmit Singh
Asmit Singh il 30 Mag 2021
You can do this by mapping 2 consecutive indices to one index, ie. {1, 2} to 1, {3,4} to 2 and so on.. The following code should help
x = randi([0,1],1,n);%n is input from a text box
for i=1:2:length(x)%i verify from 2 in 2 values from array
%j maps index for y to index for x
j = fix(i/2)+1;
if(x(i)==0 && x(i+1)==0)
y(j)=1;
elseif(x(i)==1 && x(i+1)==0)
y(j)=2;
elseif(x(i)==0 && x(i+1)==1)
y(j)=3;
else
y(j)=4;
end
end

Più risposte (0)

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Tag

Prodotti


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by