1
votes

I am fairly new to Matlab. I wrote a code in C++ to calculate the length of the base of triangle in respect to alpha angle, the code works as expected. Now I would like to complete the same task in Matlab and plot results.

C++ code

        #include <iostream>
        using namespace std;
        #include <tgmath.h> 

        int a = 135; 
        int b = 125;

        double base;
        double alphaB;
        double alphaC;
        double alphaA;
        float difference;

        #define PI 3.14159265358979323846

        int main() {
            for(int i = 1; i < 90; i++){

               alphaA = i * PI/180;
               alphaB = asin((b*sin(alphaA))/a);
               alphaC = 180*PI/180 - alphaA - alphaB;
               base = (a*sin(alphaC))/(sin(alphaA));

               cout << base << endl;
            }
            return 0;
        }

Matlab script

y = 0:1:90;
z = my(y);
plot(z,y)

function base = my(x)

a = 135; %Side A lenght
b = 125; %Side B lenght

 f = x * pi/180;
 alphaB = asin((b*sin(f))/a);
 alphaC = 180*pi/180 - f - alphaB;
 base   = (a*sin(alphaC))/(sin(f));
 disp(base);
end

when I run the Matlab script the output is just one number and the plot is empty, so I wrote another debugging script stripping "(a*sin (alpha)) /(sin (f))" equation into pieces

y = 1:1:5;
z = my(y);
plot(z,y)

function base = my(x)

a = 135; %Side A lenght
b = 125; %Side B lenght

 f = x * pi/180;
 alphaB = asin((b*sin(f))/a);
 alphaC = 180*pi/180 - f - alphaB;
 alphaC2 = sin(alphaC);
 sf = sin(f);
 aa = a*alphaC2;
 test = aa/sf;  % division problem
 base   = aa;
 disp(test);
 disp(aa);
 disp(sf);

end

It turns out the problem is when it comes to division, when displaying "aa,sf" I got all of the output, 90 numbers. When the script hits "test = aa/SF" I have single output(one number). How to overcome this problem?

1
Simpoe typo, use the elementwise division ./ instead of the matrix division. - Matthieu Brucher

1 Answers

3
votes

You would want to use ./ instead of /

/ is a matrix division ./ is a division of each element.