Data storage in a for loop in matlab

Click For Summary
SUMMARY

The forum discussion focuses on storing data in a vector during a for loop in MATLAB while calculating the vector field of a linear simple wave in shallow water. The user encountered an error due to attempting to access an index that must be a positive integer. The solution provided involves using two vectors, one for the depth 'h' and another for the calculated values 'x', allowing for proper indexing and data storage. The corrected code snippet uses vectorized operations to eliminate the need for a for loop, enhancing performance and readability.

PREREQUISITES
  • Understanding of MATLAB syntax and operations
  • Knowledge of vectorized programming in MATLAB
  • Familiarity with wave equations in fluid dynamics
  • Basic concepts of plotting in MATLAB
NEXT STEPS
  • Explore MATLAB vectorization techniques for performance optimization
  • Learn about MATLAB's plotting functions, specifically 'plot' and its parameters
  • Study fluid dynamics principles related to wave propagation
  • Investigate MATLAB's built-in functions for handling arrays and matrices
USEFUL FOR

MATLAB programmers, fluid dynamics researchers, and anyone interested in optimizing data storage and visualization in MATLAB for wave equations.

kbka
Messages
25
Reaction score
0
Hi!

I'm trying to write a program, to show the vector field of a linear simple wave in shallow water. First, determining the position of a particle i run into a problem when trying to store the data in a vector/array. The equation for this is given below. In this particular case everything is kept constant except the water depth h

for h = 0.1: 0.1: 3
x(h)=xi+H/2*cosh((omega/(sqrt(g*h)))*(zeta+h))/(sinh((omega/(sqrt(g*h)))*h))*sin(omega*t-(omega/(sqrt(g*h)))*xi);
end

I get the following error:

? Attempted to access x(0.1); index must be a positive integer or logical.

Help is much appreciated...

//Kbka
 
Physics news on Phys.org
I have realized that the index must be an integer. The increments need to be at least 0.1 so is there another way to store the x-values
 
You will need two vectors, one for x and one for h. This will work if all the other values are scalars:

h = 0.1:0.1:3;
x = xi + H/2 * cosh(omega./sqrt(g*h).*(zeta+h)) ./ sinh(omega./sqrt(g*h).*h) .* sin(omega*t - omega./sqrt(g*h).*xi);

As an example, in order to plot x versus h, you will just use plot(x,h).
 

Similar threads

Replies
5
Views
8K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 8 ·
Replies
8
Views
3K
  • · Replies 29 ·
Replies
29
Views
5K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K