How can i solve this error?
Info
This question is closed. Reopen it to edit or answer.
Show older comments
% 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

Answers (1)
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.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!