3. Create a function (in a function m-file) that has one inpu input will be a ve
ID: 2291541 • Letter: 3
Question
3. Create a function (in a function m-file) that has one inpu input will be a vector. The function should compute the square of each element of the input vector. This function should print the input numbers and their squares to the Command Window in two columns, with the input numbers in the first column and the squares in the second column. All numbers should be printed as integers. (In other words, no decimal points should be printed) Both columns should have right justification. (In other words, the least significant digits should line up vertically.) (40pts) t. No outputs will be returned. The Prepare a script. This script should create a vector of even integers, starting at 2 and ending at 34. Call your function with this vector as input.Explanation / Answer
clc
clear all
close all
vector=1:20;
squarefun(vector);
function []=squarefun(vector)
for i=1:length(vector)
sqv(i)=vector(i)^2;
end
fprintf('Vector Square Vector ')
fprintf('------ ---------------- ')
for j=1:length(sqv)
fprintf(' %4.0f %4.0f ',vector(j),sqv(j))
end
Output:
Vector Square Vector
------ ----------------
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
11 121
12 144
13 169
14 196
15 225
16 256
17 289
18 324
19 361
20 400
b)
clc
clear all
in=2:34;
evenfun(in);
function []=evenfun(in)
fprintf('The even numbers are: [')
for i=1:length(in)
if(mod(in(i),2)==0)
fprintf('%d ',in(i))
end
end
fprintf('] ')
Output:
The even numbers are:
[2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 ]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.