i am training now for matlab. but i can not understand how matlab works for this one f(end)?
x = [2 5 3]
f = 2
f(x) = f(end) * x
the ans is : f = [2 4 6 0 10]

답변 (1개)

Stephen23
Stephen23 2019년 9월 5일
편집: Stephen23 2019년 9월 5일

0 개 추천

When used as an index, end returns the last index (for the specific dimension, or as a linear index).
Because f is defined as a scalar in your example, f(end) is simply equal to f, so your example is trivially equivalent to:
x = [2 5 3]
f = 2
f(x) = f * x

댓글 수: 6

HAAAAH
HAAAAH 2019년 9월 5일
so f (x) should be [4 10 6] but the answer is f = [2 4 6 0 10] ?
madhan ravi
madhan ravi 2019년 9월 5일
x = [2 5 3]
f = @(x) 2 * x;
f = f(x)
Stephen23
Stephen23 2019년 9월 5일
편집: Stephen23 2019년 9월 5일
"so f (x) should be [4 10 6] ..."
I have no idea why you would expect that.
"...but the answer is f = [2 4 6 0 10] "
That is exactly what I would expect. First you defined f=2, then you allocated the data [4,10,6] to indices [2,5,3] of f. MATLAB automatically expands f to fit those indices (using default value of zero) and allocates exactly the values that you told it to.
I suspect that you have mistakenly used the syntax f(x) = ..., thinking that it somehow defines a function of x. In fact f(x) = ... is defined as indexing into f, which gives exactly the result that you show.
If you expect f = [4,10,6] then just do this:
>> f = f*x
f =
4 10 6
HAAAAH
HAAAAH 2019년 9월 5일
thanks a lot! i missunderstand f(x) .
Guillaume
Guillaume 2019년 9월 5일
And be aware that Madhan has shown you one possible way to define a function f of x. Although, I wouldn't use the last line as is as it overwrite the function with the result
x = [2, 5, 3];
f = @(x) 2*x; %note that the variable name here doesn't have to be x. It's not the same x as the 1st line
y = f(x)
Steven Lord
Steven Lord 2019년 9월 5일
Because f is defined as a scalar in your example, f(end) is simply equal to f,
I would phrase this slightly differently. Because f has only 1 element, f(end) is f(1). If f had 2 elements, f(end) would be f(2). My hope is that this would make apparent the link between the end index's value and the number of elements in f.
It also generalizes: if f has 5 rows, f(end, 1) is f(5, 1). If f has 7 columns, f(3:4, end) is f(3:4, 7) and f(4, end-1) is f(4, 7-1). Just replace end with the size of f in the corresponding dimension.

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

카테고리

도움말 센터File Exchange에서 MATLAB에 대해 자세히 알아보기

질문:

2019년 9월 5일

댓글:

2019년 9월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by