What is wrong on my script?

1 回表示 (過去 30 日間)
motevalizadeh
motevalizadeh 2017 年 5 月 10 日
コメント済み: motevalizadeh 2017 年 5 月 11 日
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:
  1 件のコメント
motevalizadeh
motevalizadeh 2017 年 5 月 11 日
Thank u so much :)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by