Array creation with condition from another array

6 ビュー (過去 30 日間)
Sferle Alin-Tudor
Sferle Alin-Tudor 2021 年 5 月 30 日
コメント済み: Sferle Alin-Tudor 2021 年 5 月 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 Center および File ExchangeMultidimensional Arrays についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by