Chp#7 Ex

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Q -6

tny = [31 26 30 33 33 39 41 41 34 33 45 42 36 39 37 45 43 36 41 37 32 32 35 42 38
33 40 37 36 51 50];
tanc = [37 24 28 25 21 28 46 37 36 20 24 31 34 40 43 36 34 41 42 35 38 36 35 33
42 42 37 26 20 25 31];

% a) Calculate average temperature


avg_tny = mean(tny);
avg_tanc = mean(tanc);

% b) Days below average temperature


below_avg_tny = sum(tny<avg_tny);
below_avg_tanc = sum(tanc<avg_tanc);

% c) Days with higher temperature in Anchorage


higher_temp_days = sum(tanc>tny);
higher_temp_dates = find(tanc>tny);

% d) Days with the same temperature in both cities


same_temp_days = sum(tanc == tny);
same_temp_dates = find(tanc == tny);

% e) Days with temperature above freezing in both cities


above_freezing_days = sum(tny> 32 &tanc> 32);
above_freezing_dates = find(tny> 32 &tanc> 32);

% Display the results


disp(['a) Average temperature for New York: ', num2str(avg_tny)]);
disp([' Average temperature for Anchorage: ', num2str(avg_tanc)]);
disp(['b) Days below average in New York: ', num2str(below_avg_tny)]);
disp([' Days below average in Anchorage: ', num2str(below_avg_tanc)]);
disp(['c) Days with higher temperature in Anchorage: ',
num2str(higher_temp_days)]);
disp([' Dates in the month: ', num2str(higher_temp_dates)]);
disp(['d) Days with same temperature in both cities: ',
num2str(same_temp_days)]);
disp([' Dates in the month: ', num2str(same_temp_dates)]);
disp(['e) Days with temperature above freezing in both cities: ',
num2str(above_freezing_days)]);
disp([' Dates in the month: ', num2str(above_freezing_dates)])

Q:7
function y = my_function(x)
if x >= -6 && x <= -2
y = 4 * exp(x + 2);
elseif x >= -2 && x <= 2
y = x^2;
elseif x >= 2 && x <= 6
y = (x + 62)^(1/3);
else
y = 0; % For x outside the specified ranges
end
end
x_values = -6: 0.012 :6
y_values = zeros(size(x_values));
for i = 1:length(x_values)
y_values(i) = my_function(x_values(i));
end
plot(x_values, y_values, 'LineWidth', 2);
xlabel('x');
ylabel('f(x)');
title('Plot of the given function');
grid on;

Q#8
a = input('Enter a: ');
b = input('Enter b: ');
c = input('Enter c: ');
D = b^2 - 4*a*c;
if D > 0
x1 = (-b + sqrt(D)) / (2*a);
x2 = (-b - sqrt(D)) / (2*a);
disp('Two roots:')
disp([x1, x2])
elseif D == 0
x = -b / (2*a);
disp('One root:')
disp(x)
else
disp('No real roots')
end

Q :9
matrix = zeros(4, 7);
for i = 1:4
for j = 1:7
matrix(i, j) = i + j;
end
end
disp('Resulting Matrix:')
disp(matrix)

Q:10
matrix = zeros(5, 8);
for i = 1:5 % Loop through rows (using size for clarity)
for j = 1:8 % Loop through columns
if mod(i + j, 2) == 0 % Check if sum of indices is even
matrix(i, j) = (i + j) ^ 2; % Square the sum
else
matrix(i, j) = (i + j) ^ 0.5; % Take the square root
end
end
end
disp('Resulting Matrix:')
disp(matrix)

Q:11
function result = leibniz_series_sum(m)
result = 0;
for n = 0:m
result = result + (-1)^n / (2*n + 1);
end
end
% Calculate and display the results for m = 10 and m = 500
result_10 = leibniz_series_sum(10);
result_500 = leibniz_series_sum(500);

disp(['Sum for m = 10: ', num2str(result_10)]);


disp(['Sum for m = 500: ', num2str(result_500)]);
disp(['Comparison with pi/4: ', num2str(result_500 / 4)]);

Q;12
x = [1 5 -60 8 -2 5 4 -10 0.5 3];
positive_sum = 0;
for i = 1:length(x)
if x(i) > 0
positive_sum = positive_sum + x(i);
end
end
disp('Sum of positive elements:')
disp(positive_sum)
Q: 13
num = 1; % Start from 1
while true
if mod(num, 2) == 1 && mod(num, 3) == 0 && (num^3 > 4000)
disp('The req num is:')
disp(num) % Display the result directly
break % Exit the loop
end
num = num + 2; % Check only odd numbers
end

Q:14
function y = downsort(x)
% Create a copy of the input vector to avoid modifying it
y = x;
for i = 1:length(y)-1
for j = i+1:length(y)
if y(i) < y(j)
temp = y(i);
y(i) = y(j);
y(j) = temp;
end
end
end
end

x = randi([-30, 30], 1, 14);


y = downsort(x);
disp("Original vector:");
disp(x);
disp("Sorted vector:");
disp(y);
Q: 15
function B = matrixsort(A)
B = sort(A(:));
B = reshape(B, size(A));
end
A = randi([-30, 30], 4, 7);
B = matrixsort(A);
disp("Original matrix:");
disp(A)
disp("Sorted matrix:");
disp(B)

Q:16
% Get package weight and service type from user
w = input('Enter the weight of the package (in pounds): ');
s = lower(input('Enter the type of service (Ground, Air, or Overnight): ', 's'));

% Calculate cost based on weight and service


if strcmp(s, 'ground')
if w <= 2
c = 1.50;
elseif w <= 10
c = 1.50 + (w - 2) * 0.50;
else
c = 5.50 + (w - 10) * 0.30;
end
elseif strcmp(s, 'air')
if w <= 2
c = 3.00;
elseif w <= 10
e = ceil(w - 2);
c = 3.00 + 0.90 * e;
else
e = ceil(w - 10);
c = 10.20 + 0.60 * e;
end
elseif strcmp(s, 'overnight')
if w <= 2
c = 18.00;
else
e = ceil(w - 2);
c = 18.00 + 6.00 * e;
end
else
fprintf('Invalid service type. Please enter Ground, Air, or Overnight.\n');
return;
end

% Check if the weight exceeds the maximum allowed weight for each service
type
if (strcmp(s, 'ground') || strcmp(s, 'air')) && w > 50
fprintf('Service is not available for packages exceeding 50 lb.\n');
return;
elseif strcmp(s, 'overnight') && w > 10
fprintf('Service is not available for packages exceeding 10 lb.\n');
return;
end

% Display the cost


fprintf('The cost of %s service for a %.1f lb package is $%.2f\n', s, w, c);

Q :17
x = 1:50;
filtered_x = x(~(mod(x, 3) == 0 | mod(x, 4) == 0 | mod(x, 5) == 0));
disp("Original vector:")
disp(x)
disp("New vector after removing elements divisible by 3, 4, or 5:")
disp(filtered_x)

Q:18
function [theta, radius] = CartesianToPolar(x, y)
% Calculate radius
r = sqrt(x^2 + y^2);

% Calculate theta in degrees


t = atan2d(y, x);
end

% Example usage for specified points


x1 = 15; y1 = 3;
[t1, r1] = CartesianToPolar(x1, y1);
disp(['For point (', num2str(x1), ', ', num2str(y1), '):']);
disp([' Polar Coordinates: Theta = ', num2str(t1), ' degrees, Radius = ',
num2str(r1)]);

x2 = -7; y2 = 12;
[t2, r2] = CartesianToPolar(x2, y2);
disp(['For point (', num2str(x2), ', ', num2str(y2), '):']);
disp([' Polar Coordinates: Theta = ', num2str(t2), ' degrees, Radius = ',
num2str(r2)]);

x3 = 17; y3 = -9;
[t3, r3] = CartesianToPolar(x3, y3);
disp(['For point (', num2str(x3), ', ', num2str(y3), '):']);
disp([' Polar Coordinates: Theta = ', num2str(t3), ' degrees, Radius = ',
num2str(r3)]);

x4 = 10; y4 = -6.5;
[t4, r4] = CartesianToPolar(x4, y4);
disp(['For point (', num2str(x4), ', ', num2str(y4), '):']);
disp([' Polar Coordinates: Theta = ', num2str(t4), ' degrees, Radius = ',
num2str(r4)]);

Q :19
function V = Vfuel(h)
r = 0.4;
L = 1.2;
Vcyl = pi * r^2 * h;
Vcap = (2/3) * pi * r^3;
V = Vcyl + 2 * Vcap;
V = min(V, pi * r^2 * L);
end
h = 0:0.01:2;
V = Vfuel(h);
% Ensure the grid is displayed
grid on;
plot(h, V);
xlabel('Height (m)');
ylabel('Volume (m^3)');
title('Fuel Volume in Cylindrical Tank with Hemispherical Caps');

Q:20
function v = velocity(t)
% Calculate velocity based on the piecewise function
v = zeros(size(t));

% For 0 <= t <= 10s


indices = t <= 10;
v(indices) = 1.4 * t(indices);

% For 10 < t <= 25s


indices = t > 10 & t <= 25;
v(indices) = 14 + 5 * sin(pi / 10 * (t(indices) - 10));

% For 25 < t <= 35s


indices = t > 25 & t <= 35;
v(indices) = 9;

% For 35 < t <= 40s


indices = t > 35 & t <= 40;
v(indices) = 9 - 9/5 * (t(indices) - 35);
end

function a = acceleration(t)
% Calculate acceleration based on the derivative of the velocity function
dt = 1e-3; % Small time step for numerical differentiation
v = velocity(t);
v_next = velocity(t + dt);
a = (v_next - v) / dt;
end

% Create vector of time values


t = 0:0.01:40;

% Calculate velocity and acceleration vectors


v = velocity(t);
a = acceleration(t);

% Plot velocity
subplot(2,1,1);
plot(t, v);
xlabel('Time (s)');
ylabel('Velocity (m/s)');
title('Velocity vs. Time');

% Plot acceleration
subplot(2,1,2);
plot(t, a);
xlabel('Time (s)');
ylabel('Acceleration (m/s^2)');
title('Acceleration vs. Time');

Q : 21
function W = scale(x)
% Given parameters
k1 = 800; % N/m
k2 = 1700; % N/m
d = 0.02; % 20 mm converted to meters

% Calculate the equivalent spring constant k


k = 1 / ((1/k1) + (1/k2));

% Calculate the weight W using Hooke's Law


W = k * x / d;
end

% a) Determine the weight for tray displacements of 1.5 and 3.1 cm


disp('Weight for 1.5 cm displacement:');
W1 = scale(0.015)
disp('Weight for 3.1 cm displacement:');
W2 = scale(0.031)

% b) Plot the weight as a function of displacement for 0 ≤ x ≤ 4 cm


x_values = 0:0.01:0.04; % Displacement values from 0 to 4 cm
W_values = arrayfun(@scale, x_values);

% Plotting
figure;
plot(x_values * 100, W_values, 'LineWidth', 2);
xlabel('Tray Displacement (cm)');
ylabel('Weight (N)');
title('Weight vs Displacement');
grid on;

Note : We use “ strcmpi(s, 'ground') ” in Program :16 because


If you use `if lower(s) == 'ground'` instead of `if strcmpi(s, 'ground')`, the
comparison will not work correctly. Here's why:

1. `lower(s)` converts the entire string `s` to lowercase.

2. `== 'ground'` compares the entire string `lower(s)` to the string `'ground'`.

This comparison will only evaluate to true if the lowercase version of the input
string `s` is exactly `'ground'`. However, if the user inputs `'Ground'`,
`'GROUND'`, or `'grOund'`, the comparison will fail because these strings are not
exactly equal to `'ground'`.

In contrast, `strcmpi(s, 'ground')` performs a case-insensitive comparison,


meaning it will return true if the input string `s` is equal to `'ground'` regardless
of its case (`'Ground'`, `'GROUND'`, `'grOund'`, etc.).

Therefore, using `strcmpi(s, 'ground')` is more robust and flexible for checking
whether the input service type is `'ground'` irrespective of its case.

You might also like