필터 지우기
필터 지우기

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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by