Array creation with condition from another array

6 次查看(过去 30 天)
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.

采纳的回答

Asmit Singh
Asmit Singh 2021-5-30
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by