plot a function of 2 variables inside a for loop
5 views (last 30 days)
Show older comments
I have this equation where A,B are onstants and E= ( 1-( ((1-B)/2.*J).*(1+(E.*J/(A*B)))*sqrt(E.*J.*A/B) ));
I need to plot E as J varies from 0:300 however when I evaluate E inside a for loop from 0:300 using solve command I get error in using indices. This is the piece of code:
A=5;
B=0.9;
J=0:300;
syms E J
for i= 1:lenght(j)
E(i)= solve(( 1-( ((1-B)/2.*J(i)).*(1+(E(i).*J(i)/(A*B)))*sqrt(E(i).*J(i).*A/B) )),J(i));
end
0 Comments
Accepted Answer
Rik
on 7 Dec 2021
You are overwriting J and using j in your loop definition.
You should define an array to hold the result. Then you can define E as a symbolic variable. Since J has a definite value, it is not symbolic.
Also, don't use i or j as variable names and use numel or size instead of length.
The last change you need to make is to not index E. You could also use J directly in the for loop definition, but that is a matter of taste.
3 Comments
Rik
on 7 Dec 2021
A= 0.9;
B= 5;
J= 1:300;
E_sol=zeros(size(J));
syms E
w=warning('off','symbolic:solve:PossiblySpuriousSolutions');
for k=1:numel(J)
%You should solve for E, since you want to know the value of E
tmp=solve(( 1-( ((1-B)/2.*J(k)).*(1+(E.*J(k)/(A*B)))*sqrt(E.*J(k).*A/B) )),E);
if k==1,tmp,end %debug information
tmp=double(tmp);
if k==1,tmp,end %debug information
%You probably want to select the real solution
[imag_val,ind]=min(abs(imag(tmp)));
if imag_val > 2*eps
warning('J=%.0f did not return a real solution',J(k))
E_sol(k)=NaN;
continue
end
E_sol(k)=tmp(ind);
end
warning(w);%reset warning state
E_sol
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!