Clear Filters
Clear Filters

how do i put multiple data into an equation using for loop

4 views (last 30 days)
Hi all, I have an array of numbers that i want to insert into an equation and then plot a graph using surf, but I can't figure out how to put the data that I have into the equation. I;m trying to do a loop function for this
t=linspace(0,2,100)
x=linspace(0,10,100)
n1=0
n2=0
for n1=0:t
for n2=0:x
U=10*sin(2*pi*(n1-n2/5)+2*sin(2*pi*(n1+n2/5)))
end
end
disp(U)
This is how I did it but all it show is the linspace of t and x
I attached a screenshot of the actual equation
any help is appreciated
  1 Comment
Yaswanth Sai Jetti
Yaswanth Sai Jetti on 8 Dec 2020
You can use mesh grid to generate the 2D data and then plot using surf. Here is the code for it:
[t,x] = meshgrid(linspace(0,2,100),linspace(0,10,100));
U = 10*sin(2*pi*(t-x/5)+2*sin(2*pi*(t+x/5)));
surf(t,x,U);
contourf(t,x,U);
If you want to use the for loop, you should try something like this,
t=linspace(0,2,100);
x=linspace(0,10,100);
U = zeros(100);
for n1=1:100
for n2=1:100
U(n2,n1)=10*sin(2*pi*(t(n1)-x(n2)/5)+2*sin(2*pi*(t(n1)+x(n2)/5)));
end
end
However, you still need to use the meshgrid function to genrate the 2D data for t and x.

Sign in to comment.

Answers (1)

Cris LaPierre
Cris LaPierre on 8 Dec 2020
Your for loops are not working as you expect because the syntax is incorrect. You can learn more and see some examples on the documentation page here. For loops are also comvered in Ch 13 of MATLAB Onramp. You should also go through Ch 5 to learn about how to use an index to store and access values in an array.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!