Array creation with condition from another array

6 Ansichten (letzte 30 Tage)
Sferle Alin-Tudor
Sferle Alin-Tudor am 30 Mai 2021
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.

Akzeptierte Antwort

Asmit Singh
Asmit Singh am 30 Mai 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

Weitere Antworten (0)

Kategorien

Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by