MATLAB Answers

Error when solving symbolic equation in nested for loop

3 views (last 30 days)
Brian Nyaberi
Brian Nyaberi on 24 Oct 2019
Edited: Stephan on 24 Oct 2019
I am trying to solve a symbolic equation for b in a nested as shown below but i am getting the following error:
Error in solve (line 226)
[eqns,vars,options] = getEqns(varargin{:});
Error in Problem_1 (line 20)
s1=solve(tand(t(j))==2*cotd(b).*((M1(i).^2*sind(b).^2-1)./(M1(i).^2*(G+cosd(2*b))+2)),b); %solve for beta
Here is the code:
clc
clear
syms b x
M1 = [1.6,1.8,2.0,2.2,2.6,3.2,4.0];
t = [0,8,16,24,32,40];
%M1 = 6; %Mach number M1
%t = 6; %Deflection angle theta
G = 1.4; %gamma
M = numel(M1); %Number of Mach 1 elements
T = numel(t); %Number of theta elements
Mach2 = zeros(M,T); %Matrix for M2
P_rat = zeros(M,T); %Matrix for Pressure ratio
for i=1:M
for j=1:T
s1=solve(tand(t(j))==2*cotd(b).*((M1(i).^2*sind(b).^2-1)./(M1(i).^2*(G+cosd(2*b))+2)),b); %solve for beta
b = double(s1)+180; %beta
end
end

  0 Comments

Sign in to comment.

Accepted Answer

Stephan
Stephan on 24 Oct 2019
Edited: Stephan on 24 Oct 2019
The first time your loop runs free of errors, but then your code is selfkilling, because you cast the symbolic variable b to be a type double. This will not be reseted during the run of your loop, which means that in the second run the error occurs, due to b is a type double now and no more symbolic. To solve this i renamed the result to bb and left b for the symbolic variable.
In addition you should not name loop indices i or j - because of possible problems when working with complex numbers. Many people use ii and jj instead.
A further point is that you seem to overwrite the result in everey run of your loop. I allowed myself to save the results in a cell array, so that you have access to all results:
clc
clear
syms b x
M1 = [1.6,1.8,2.0,2.2,2.6,3.2,4.0];
t = [0,8,16,24,32,40];
bb = cell(numel(M1),numel(t));
%M1 = 6; %Mach number M1
%t = 6; %Deflection angle theta
G = 1.4; %gamma
M = numel(M1); %Number of Mach 1 elements
T = numel(t); %Number of theta elements
Mach2 = zeros(M,T); %Matrix for M2
P_rat = zeros(M,T); %Matrix for Pressure ratio
for ii=1:M
for jj=1:T
s1=solve(tand(t(jj))==2*cotd(b).*((M1(ii).^2*sind(b).^2-1)...
./(M1(ii).^2*(G+cosd(2*b))+2)),b); %solve for beta
bb{ii,jj} = double(s1)+180; %beta
end
end

  0 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by