loop iteration using alphabet and then its indexing

6 views (last 30 days)
Hi,I'm trying to iterate loop using alphabet and then want to use that alphabet for indexing of my predefined array variables.The idea of doing this just to shorten the code instead of writing same formula 4 times for each array a,b,c, and d.I'm getting invalid indexing error.Can someone help me what I'm trying to do.I'll really appreciate your help.Also when I run this code clc,clear,etc not working even after running the code several times.I don't know why.Here is what I've written
clc;clear;close;
%define variables
syms x y z
%write all velocity vectors
a=[x*y^2,2*y*x^2,10];
b=[x^2+y^2+z^2,x*y+y*z+z^2,-3*x*z-z^2/2+4];
c=[x*y*z^2,x^2*y*z,z*x*y^2];
d=[x^2/2,y^2/2,3*z^2];
%determine rotation vectors for 'a'
%a(1) is 'u',a(2) is 'v' and a(3) is 'w'
for var='a':'d'
omega_x=(diff(str2sym(var)(3),y)-diff(str2sym(var)(2),z))/2;
omega_y=(diff(str2sym(var)(1),z)-diff(str2sym(var)(3),x))/2;
omega_z=(diff(str2sym(var)(2),x)-diff(str2sym(var)(1),y))/2;
%now print omega in vector form
fprintf('Omega_%s = (%s)i+(%s)j+(%s)k\n\n',var,omega_x,omega_y,omega_z)
%check for irrotationality
if omega_x==0 && omega_y==0 && omega_z==0
disp('This flow field is irrotational')
end
end

Accepted Answer

Walter Roberson
Walter Roberson on 13 Sep 2021
vars = {a, b, c, d};
for varidx = 1 : length(vars)
var = vars{varidx};
omega_x=(diff(var(3),y)-diff(var(2),z))/2;
and so on
end
  4 Comments
ajeet sahu
ajeet sahu on 13 Sep 2021
Got the right answer by small modification.Needed to make different array for names a,b,c, and d.Thankyou for your help.I've accepted your answer.Here is the complete code.
clc;clear;close;
%define variables
syms x y z
names=['a','b','c','d'];
%write all velocity vectors
a=[x*y^2,2*y*x^2,10];
b=[x^2+y^2+z^2,x*y+y*z+z^2,-3*x*z-z^2/2+4];
c=[x*y*z^2,x^2*y*z,z*x*y^2];
d=[x^2/2,y^2/2,3*z^2];
%determine rotation vectors for 'a'
%a(1) is 'u',a(2) is 'v' and a(3) is 'w'
vars = {a, b, c, d};
for i = 1 : length(vars)
var=vars{i};
omega_x=(diff(var(3),y)-diff(var(2),z))/2;
omega_y=(diff(var(1),z)-diff(var(3),x))/2;
omega_z=(diff(var(2),x)-diff(var(1),y))/2;
%now print omega in vector form
fprintf('Omega_%s = (%s)i+(%s)j+(%s)k\n\n',names(i),omega_x,omega_y,omega_z)
%check for irrotationality
if omega_x==0 && omega_y==0 && omega_z==0
disp('This flow field is irrotational')
end
end

Sign in to comment.

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!