OBJECTIVE: To demonstrate competence creating and manipulating arrays in MATLAB.
ID: 3682516 • Letter: O
Question
OBJECTIVE: To demonstrate competence creating and manipulating arrays in MATLAB.
You should work on this task individually.
Write a script (cfu.m) that prompts the user for the values a, b, m, and n and then creates the array A that contains all numbers between m and n that are divisible by a but not divisible by b. Here, “divisible” means the division has a remainder of 0. Your script should print A and output the number of elements in A.
You may not use loops. You must use only array manipulations.
Hints:
Always plan your code before you write your code.
Logical indexing allows you to select elements in a list that match a given condition.
A(A > 19) selects the elements in A that are greater than 19
The mod function returns the remainder after division.
mod(2019,15) = 9
Example:
>> cfu
a: 5
b: 3
m: 1
n: 100
14 numbers between 1 and 100 are divisible by 5 but not by 3:
5 10 20 25 35 40 50 55 65 70 80 85 95 100
>>
Explanation / Answer
clc
clear
% Taking input for a b m & n from user
a = input('a: ');
b = input('b: ');
m = input('m: ');
n = input('n: ');
%creating the array A
A = m:n; %creates array of number between m and n
A = A(mod(A,a)==0); %selects the elemnts divisible by a
A = A(mod(A,b)~=0); %selects the elements not divisible by b
l = length(A); %getting number of elements in A
%creating string to display
string = sprintf('%d numbers between %d and %d are divisible by %d but not by %d:',l,m,n,a,b);
disp(string) %displaying the string
disp(A) %displaying the array A
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.