Reaching the element of an array passed to a function

조회 수: 1 (최근 30일)
Hsin-Hua Wang
Hsin-Hua Wang 2017년 3월 4일
댓글: Hsin-Hua Wang 2017년 3월 7일
I'm trying to create a function y=f(x) composed of two different parts for x < constant C & x >= C. When one pass an array A to f(x), the return would be an array B where Bij=f(Aij) How do I create a valid "if statement" in the function f? Below is the code I'm using (say I want to create a step function) What happened is since A is an array, all statement would be false Is there a way to call the "current" element in array A?
function y=f(A)
if A >= C
y=0
elseif A<C
y=1
end
end

채택된 답변

Sky Sartorius
Sky Sartorius 2017년 3월 4일
The first step needs to be to find the indices of the array that correspond to the conditional statement. You can use something like find for this, but logical indexing is usually preferred.
y = ones(size(A)); % Set up y.
ind = A >= C; % First, find elements of A that are greater than C.
y(ind) = 0;
y(~ind) = 1;
The last line is not absolutely necessary in this case, since we initialized y using ones, but you could put an equation here if something more complicated was needed.
  댓글 수: 1
Hsin-Hua Wang
Hsin-Hua Wang 2017년 3월 7일
Thank you! this is what I need to know, logical indexing.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2017년 3월 4일
편집: Image Analyst 2017년 3월 4일
Why not just do
B = A < C;
Why bother making a function at all when a simple one-liner will do it?
You're either over-thinking it or I'm not understanding what you want. So please post examples with x, y, A, B, and/or C so we can see what you want.
  댓글 수: 1
Hsin-Hua Wang
Hsin-Hua Wang 2017년 3월 7일
I'm actually trying to make a more complex function and was just using step function as an example. Thanks still!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by