What is wrong on my script?

1 次查看(过去 30 天)
I'm new on matlab, and sorry if my question is simple :)
I have a function and call it on my main script
function [ f ] = fitness( x )
f =x(2);
end
My main script:
clc;
clear all;
close all;
fl=fitness( 2 );
display(fl);
and i have got this error:
Index exceeds matrix dimensions.
Error in fitness (line 3)
f=x(2);
What is wrong?

采纳的回答

Stephen23
Stephen23 2017-5-10
编辑:Stephen23 2017-5-10
Inside your function fitness you obtain the second element of x using this line of code:
f =x(2);
but when you call your function fitness you only provide a 1x1 input, so there is no second element of x (when x is scalar it has only one element, so it is an error to try and get the second element: it does not exist!). Note that the number 2 is a scalar array (i.e. 1x1 array), so it has no second element:
fl=fitness( 2 );
You do not explain what you are trying to do, nor what you expect to happen, so it is hard to give any advice on how to fix this. One option is to provide an input with atleast two elements:
fl=fitness([1,3,5]);
but this might not be what you intended. Note that these very basic concepts, such as different array sizes, how to access their elements, and how to call functions are introduced in the Introductory Tutorials, which are highly recommended for all beginners:
You might like to read this as well, for some tips and hints for the future:

更多回答(0 个)

类别

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