My function won't accept the vector

10 ビュー (過去 30 日間)
Natalie
Natalie 2023 年 1 月 6 日
コメント済み: Natalie 2023 年 1 月 7 日
x = 0:1:10;
f(x) = x.^2-x-1;
I keep getting an error message saying Array indices must be positive integers or logical values. I am trying to find values of f(x) within certain parameters using the find function.

採用された回答

Arif Hoq
Arif Hoq 2023 年 1 月 7 日
移動済み: Image Analyst 2023 年 1 月 7 日
You can not specify 0 as an index
x = 0:1:10;
f = x.^2-x-1
f = 1×11
-1 -1 1 5 11 19 29 41 55 71 89
  1 件のコメント
Natalie
Natalie 2023 年 1 月 7 日
This Fixed my problem thank you very much for the help

サインインしてコメントする。

その他の回答 (3 件)

Walter Roberson
Walter Roberson 2023 年 1 月 7 日
x = 0:1:10;
okay, x is a list of values [0 1 2 3 4 5 6 7 8 9 10]
f(x) = x.^2-x-1;
you have to substitute in that list of values, so your statement is effectively
f(0:10) = (0:10).^2-(0:10)-1;
which tries to assign to index 0, 1, 2, ... 10. But MATLAB does not permit index 0, so you have a problem.
You could write
f(x+1) = x.^2-x-1;
which would then be equivalent to
f((0:10)+1) = (0:10).^2-(0:10)-1;
which would assign to index locations 1, 2, 3... 11.
But if you are going to define x that way, you might easily have wanted to do something like
x = 0:0.1:10;
and if you add 1 to that you would just end up with indices such as 1, 1.1, 1.2, and so on. Non-integer indices are not permitted either.
  2 件のコメント
Walter Roberson
Walter Roberson 2023 年 1 月 7 日
When you have a statement such as
f(x) = x.^2-x-1;
you need to decide whether you are working with arrays or if you are working with formulas .
If you are working with arrays, then the (x) part of f(x) has to be non-negative integers.
If you are working with formulas then the (x) on the left has to be a symbolic variable (Symbolic Toolbox)
syms x
f(x) = x.^2-x-1;
X = 0:1:10;
plot(X, f(X))
Walter Roberson
Walter Roberson 2023 年 1 月 7 日
You should learn this programming pattern: you will use it a lot.
%can be negative, non-integer, can include duplicates,\
% does not need to be sorted
xvals = -1:.1:1;
num_x = numel(xvals); %how many are there?
f = zeros(size(xvals)); %pre-allocate output same size as input
for xidx = 1 : num_x %loop over INDICES
x = xvals(xidx); %pull out one SPECIFIC value into your x
y = x.^2-x-1; %calculate based on that ONE x
f(xidx) = y; %store into a location according to the INDEX
end
plot(xvals, f) %use the entire vector of values, NOT plot(x, f)

サインインしてコメントする。


Adam Danz
Adam Danz 2023 年 1 月 7 日
移動済み: Image Analyst 2023 年 1 月 7 日
Perhaps you're looking for
x = 0:1:10;
f = x.^2-x-1;

Image Analyst
Image Analyst 2023 年 1 月 7 日
See the FAQ:
You probably want
x = 0:1:10;
f = x.^2-x-1
f = 1×11
-1 -1 1 5 11 19 29 41 55 71 89

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by