plot a function of 2 variables inside a for loop

5 views (last 30 days)
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

Accepted Answer

Rik
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
Kim Ibrahim
Kim Ibrahim on 7 Dec 2021
and when I use indexing for both E and J i get "Unable to perform assignment because the left and right sides have a different number of elements."
Rik
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
tmp = 
tmp =
0.9477 + 0.0000i -4.9738 - 2.2222i -4.9738 + 2.2222i
Warning: J=50 did not return a real solution
Warning: J=100 did not return a real solution
Warning: J=150 did not return a real solution
Warning: J=200 did not return a real solution
Warning: J=250 did not return a real solution
Warning: J=300 did not return a real solution
warning(w);%reset warning state
E_sol
E_sol = 1×300
0.9477 0.1523 0.0483 0.0209 0.0108 0.0063 0.0040 0.0027 0.0019 0.0014 0.0010 0.0008 0.0006 0.0005 0.0004 0.0003 0.0003 0.0002 0.0002 0.0002 0.0001 0.0001 0.0001 0.0001 0.0001 0.0001 0.0001 0.0001 0.0001 0.0001

Sign in to comment.

More Answers (0)

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!