Index exceeds the number of array elements (0) error. Help please

1 view (last 30 days)
Hi,
Below is my very simple code. What is wrong with this. Could you help me please?
function [E]=mainy()
clc
clear all
syms x t eta zeta xsi m tau epsilon k
for j=1:3
WK=[];
w(j)=j*2*x
end
for k=1:3
UXT=[];
UXT(k)=k*x
end
for i=1:3
E=[];
E=UXT(i)-WK(i)
% E=(UXT(k)-WK(k))/(UXT(k))
end
end
  2 Comments
OZGUR YILDIRIM
OZGUR YILDIRIM on 3 Mar 2021
I dont have time for long course. Why dou you answer like this Kalyan? What is wrong with you? If you think my question is simple then just skip.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 3 Mar 2021
Edited: Walter Roberson on 3 Mar 2021
It is not advisable to use clc inside most functions. There is not typically a reason to clear the command window.
You should never "clear all" inside a function. If you use "clear all" at all, it should only be inside one script that you use to reset the state of MATLAB when you switch tasks. "clear all" inside a function is like Wyle E. Coyote blowing up the bridge he is standing on.
Setting a variable to [] in every iteration of a loop is not productive in most cases. If the variable is not being set to something else inside the loop before being set to [] then you are just wasting time.
Every iteration of for j you clear all of WK, making it into an array of size 0. Then in for i you try to access WK(1) on the first iteration, but offset (1) is not there because you wrote [] to WK (multiple times)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!