How can i solve this error?

% formation of cartesian grid
clc,clear
x=[];
prompt = 'Number of nodes: ';
n= input(prompt);
prompt= 'Enter the length of nodes:';
L=input(prompt);
prompt = ' Enter cont/exp factor:';
b=input(prompt);
sum=1.0;
for i=1:n-2
sum= sum+ b^i;
dx=(L/sum);
end
for i=1:n-2
x(i)=x(i-1)+(dx*b^(i-1));
end
Capture.JPG

Answers (1)

Adam Danz
Adam Danz on 22 Feb 2019
Edited: Adam Danz on 25 Feb 2019
The for-loop starts with 1 and upon the first iteration, x(i-1) is the same as x(0) which causes the error 'Array indices must be positive integers or logical values'. In Matlab, the first index is 1, not 0.
Note that there are other problems or hazards in the code.
  • Avoid using 'sum' as a variable name since it's a commonly used function.
  • If the user enters a number of nodes less than 2, the for-loop will fail. That can be fixed with clearer prompt instructions or a conditional that checks the input value and throws an error when appropriate.
  • The other inputs can be similarly checked.
  • The for loops could probably be replaced with vectorized codes.
Please feel free to ask any follow-up questions.

This question is closed.

Asked:

on 22 Feb 2019

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!