Question

Translate this matlab code to python title('Starting Number vs Number of Elements in Seq') ylabel('Number of...

Translate this matlab code to python

title('Starting Number vs Number of Elements in Seq')
ylabel('Number of Elements in the sequence in the sequence')
xlabel('Starting Number')
steps = [];
vec = 1:25;

for i=1:length(vec)
s = [];
num = i;
while true
s(length(s)+1) = num;
if num == 1
break;
elseif mod(num, 2) == 0
num = num/2;
else
num = (3*num)+1;
end
end
fprintf('%d = ', i)
disp(s)
fprintf('\n')
steps(i) = length(s);
end

plot(vec, steps)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code:

import numpy as np
import matplotlib.pyplot as plt

steps = []
vec = np.arange(1, 25 + 1)

for i in range(1, len(vec) + 1):
    s = []
    num = i
    while True:
        s.append(num)
        if num == 1:
            break
        elif num % 2 == 0:
            num = num / 2
        else:
            num = (3 * num) + 1
    print('=', i)
    print(s)
    print('\n')
    steps.append(len(s))

plt.plot(vec, steps, 'ro-')
plt.title('Starting Number vs Number of Elements in Seq')
plt.ylabel('Number of Elements in the sequence in the sequence')
plt.xlabel('Starting Number')

Output:

= 1
[1]


= 2
[2, 1.0]


= 3
[3, 10, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 4
[4, 2.0, 1.0]


= 5
[5, 16, 8.0, 4.0, 2.0, 1.0]


= 6
[6, 3.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 7
[7, 22, 11.0, 34.0, 17.0, 52.0, 26.0, 13.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 8
[8, 4.0, 2.0, 1.0]


= 9
[9, 28, 14.0, 7.0, 22.0, 11.0, 34.0, 17.0, 52.0, 26.0, 13.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 10
[10, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 11
[11, 34, 17.0, 52.0, 26.0, 13.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 12
[12, 6.0, 3.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 13
[13, 40, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 14
[14, 7.0, 22.0, 11.0, 34.0, 17.0, 52.0, 26.0, 13.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 15
[15, 46, 23.0, 70.0, 35.0, 106.0, 53.0, 160.0, 80.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 16
[16, 8.0, 4.0, 2.0, 1.0]


= 17
[17, 52, 26.0, 13.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 18
[18, 9.0, 28.0, 14.0, 7.0, 22.0, 11.0, 34.0, 17.0, 52.0, 26.0, 13.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 19
[19, 58, 29.0, 88.0, 44.0, 22.0, 11.0, 34.0, 17.0, 52.0, 26.0, 13.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 20
[20, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 21
[21, 64, 32.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 22
[22, 11.0, 34.0, 17.0, 52.0, 26.0, 13.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 23
[23, 70, 35.0, 106.0, 53.0, 160.0, 80.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 24
[24, 12.0, 6.0, 3.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]


= 25
[25, 76, 38.0, 19.0, 58.0, 29.0, 88.0, 44.0, 22.0, 11.0, 34.0, 17.0, 52.0, 26.0, 13.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]
Add a comment
Know the answer?
Add Answer to:
Translate this matlab code to python title('Starting Number vs Number of Elements in Seq') ylabel('Number of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • MATLAB code starts here --------- clear T0=2; w0=2*pi/T0; f0=1/T0; Tmax=4; Nmax=15; %--- i=1; for t=-Tmax: .01:Tmax...

    MATLAB code starts here --------- clear T0=2; w0=2*pi/T0; f0=1/T0; Tmax=4; Nmax=15; %--- i=1; for t=-Tmax: .01:Tmax T(i)=t; if t>=(T0/2) while (t>T0/2) t=t-T0; end elseif t<=-(T0/2) while (t<=-T0/2) t=t+T0; end end if abs(t)<=(T0/4) y(i)=1; else y(i)=0; end i=i+1; end plot(T,y),grid, xlabel('Time (sec)'); title('y(t) square wave'); shg disp('Hit return..'); pause %--- a0=1/2; F(1)=0; %dc freq C(1)=a0; for n=1:Nmax a(n)=(2/(n*pi))*sin((n*pi)/2); b(n)=0; C(n+1)=sqrt(a(n)^2+b(n)^2); F(n+1)=n*f0; end stem(F,abs,(C)), grid, title(['Line Spectrum: Harmonics = ' num2str(Nmax)]); xlabel('Freq(Hz)'), ylabel('Cn'), shg disp('Hit return...'); pause %--- yest=a0*ones(1,length(T)); for n=1:Nmax yest=yest+a(n)*cos(2*n*pi*T/T0)+b(n)*sin(2*n*pi*T/T0);...

  • I need this program in MATLAB with different or another code. INPUT: x = [0 1...

    I need this program in MATLAB with different or another code. INPUT: x = [0 1 8 12 27]; y = [1 2 3 4 5]; nx = length(x); ny = length(y); n = length(x); if nx ~= ny display('Error. La cantidad de datos en x no es igual que los datos en y') end Sx = sum(x); Sxx = sum(x.^2); Sy = sum(y); Sxy = sum(x.*y); a1 = (n*Sxy - Sx*Sy)/(n*Sxx-(Sx)^2); a0 = (Sxx*Sy - Sxy*Sx)/(n*Sxx - (Sx)^2); m...

  • Hello, i have this matlab code where i have to track a red ball from and...

    Hello, i have this matlab code where i have to track a red ball from and uploaded video, and plot its direction in x-y direction My Question is how can i add x vs time plot and y vs time plot in this code. Thank you if exist('V','var') delete(V); end clear;clc; V=VideoReader('video.mp4'); figure(1); x=[];y=[]; i=1; while hasFrame(V) J=readFrame(V); figure(1);imshow(J);title(['Frame No. ',num2str(i)]); if (i>=28 && i<=132) bw=J(:,:,1)>200 & J(:,:,2)<80 & J(:,:,3)<80; bw=imfill(bw,'holes'); A=regionprops(bw,'Centroid'); x(end+1)=A.Centroid(1); y(end+1)=A.Centroid(2); hold on; plot(x,y,'*k');hold off; end i=i+1;...

  • I am creating a MATLAB game for my school project. The goal of the game is...

    I am creating a MATLAB game for my school project. The goal of the game is to create a 'Treasure Hunt Game' that asks the user to input the number of players, the difficult (easy, medium, or hard), and asks the user(s) to pick spots on a matrix until the correct spot is chosen, therefore winning the game. If a player misses the spot, the command window doesn't show how far away the treasure is, but what direction it is...

  • These instructions are written with the assumption that code will be done in matlab. You might fi...

    These instructions are written with the assumption that code will be done in matlab. You might find the following built in commands useful: length, plot, xlabel, ylabel, title, legend, fzero, plot, disp, axis, axes, min, max. 2. Numerical Integration (Quadrature). Write FOUR of your own numerical integration routines. One should use left-end, right-end, or mid-points, another should use the trapezoid method, another should use Simpson’s method, and the fourth should use either Guassian Quadrature or Romberg’s method. Use your four...

  • 2. (15 marks) Consider the abstract datatype SEQ whose objects are sequences of elements and whic...

    do (b) please 2. (15 marks) Consider the abstract datatype SEQ whose objects are sequences of elements and which supports two operations . PREPEND(x, S), which inserts element r at the beginning of the sequence S and . ACCESS(S, i), which returns the ith element in the sequence Suppose that we represent S by a singly linked list. Then PREPEND(, S) takes 1 step and ACCESS(S, i) takes i steps, provided S has at least i elements Suppose that S...

  • % Bisection.m Lines of code 17-26 and 43-47 are bold % This code finds the root...

    % Bisection.m Lines of code 17-26 and 43-47 are bold % This code finds the root of a function f(x) in the interval [a, b] using the Bisection method % % It uses f.m to define f(x), and assumes f(x) is continuous % It requires specification of a, b and the maximum error % It defines error using |f(xnew)| % Define inputs for problem a=0; %Defines lower limit of initial bracketing interval b=1; %Defines upper limit of initial bracketing interval...

  • MATLAB code for a double pendulum. Please explain each lines for these codes pls. -------------------------------------...

    MATLAB code for a double pendulum. Please explain each lines for these codes pls. ---------------------------------------------------------------------------- clc close all clear all %---------Parameters------------------------------------------------------ L1=1; L2=1 ; M_1=2 ; M_2=1; G=9.8; %---------initial condition----------------------------------------------- tspan=30; theta1=3; theta1_prime=0; theta2=2.5; theta2_prime=0; y0=[theta1 theta1_prime theta2 theta2_prime]; [t,y]=ode45(@pend, [0 ,tspan],[ 3 0 2 0]); %---position of mass 1 and mass 2---------------------------------------- x1=L1*sin(y(:,1)); y1=-L1*cos(y(:,1)); x2=L1*sin(y(:,1))+l2*sin(y(:,3)); y2=-L1*cos(y(:,1))-l2*cos(y(:,3)); %------visualizing the result--------------------------------------------- figure(1) plot(x1,y1,'linewidth',2) hold on plot(x2,y2,'r','linewidth',2) h=gca; get(h,'fontSize') set(h,'fontSize',14) xlabel('X','fontSize',14); ylabel('Y','fontSize',14); title('Chaotic Double Pendulum','fontsize',14) fh = figure(1); set(fh, 'color', 'white'); figure(2)...

  • Matlab problem using newton raphson to find square root of number

    Need help modifying my Matlab script below (myscript calculates the square root of a number. using a Newton-Raphson method with 1 as the initial guess, calculates true and estimated error, and shows each iteration).-I need to create three new functions each of which should be called in the main script. These functions are needed to replace code that is currently in my script shown below.-I need to create these functions:A function to find f(x)A function to find f '(x) ?A...

  • I need the code written in Matlab software to send a number of bits using the...

    I need the code written in Matlab software to send a number of bits using the Pulse Shape Modulation, and demodulate the signal using the correlation coefficient. The part that i need to modified is the part that is in Bold. The two functions are : function [outSignals,time] = modulation(inBits) and function [outBits] = demodulation(inSignals). %% Main Function function runComm_code()     clear;clc;   SNRdB = 0:0.5:26;     nBits = 1e6;     SNRdBLength = length(SNRdB);     Pe = ones(1,SNRdBLength);     clc; disp('Simulation...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT