フィルターのクリア

if loop to save number or call NaN

6 ビュー (過去 30 日間)
C.G.
C.G. 2023 年 6 月 9 日
回答済み: Govind KM 2023 年 6 月 9 日
I have 2 variables, both with 8 numbers in them.
I want to create a new variable which has 10 numbers in it using a for and and if loop.
  • If i is present in a, save the number from b with the same index
  • if i is not present in a, write NaN
This should result in a new variable c, which has 10 values in it, where 2 and 7 are presented by NaN.
Can anybody help me write this?
a = [1 3 4 5 6 8 9 10]
b = [1 2 3 3 9 7 2 2]
c = [];
for i = 1:10
%if i is present in a, save the number from b with the same index.
%if i is not present in a, write NaN.
end

回答 (1 件)

Govind KM
Govind KM 2023 年 6 月 9 日
The following code will give you the desired output :
a = [1 3 4 5 6 8 9 10];
b = [1 2 3 3 9 7 2 2];
c = [];
for i = 1:10
if any(a==i)
c(i)=b(find(a==i));
%If a can contain duplicate elements, you can use
%c(i)=b(find(a==i,1));
%This will give the index of first occurrence of i in a
else
c(i)=NaN;
end
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by