What is wrong on my script?

1 visualizzazione (ultimi 30 giorni)
motevalizadeh
motevalizadeh il 10 Mag 2017
Commentato: motevalizadeh il 11 Mag 2017
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?

Risposta accettata

Stephen23
Stephen23 il 10 Mag 2017
Modificato: Stephen23 il 10 Mag 2017
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:

Più risposte (0)

Categorie

Scopri di più su Get Started with MATLAB in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by