Filter löschen
Filter löschen

What is wrong on my script?

1 Ansicht (letzte 30 Tage)
motevalizadeh
motevalizadeh am 10 Mai 2017
Kommentiert: motevalizadeh am 11 Mai 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?

Akzeptierte Antwort

Stephen23
Stephen23 am 10 Mai 2017
Bearbeitet: Stephen23 am 10 Mai 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:

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by