The document contains the code responses to various MATLAB questions. It includes code to:
1) Calculate the complex conjugate transpose of a matrix
2) Compare two matrices element-wise and find values greater than 1
3) Extract the diagonal and superdiagonal elements of a matrix
4) Remove zero elements from a vector
5) Plot a sine function with given inputs
6) Add text to a plot at a given position
7) Define and plot a custom function
8) Calculate statistics of a matrix
9) Sort a matrix in ascending and descending order
10) Find the zero of a custom function
The document contains the code responses to various MATLAB questions. It includes code to:
1) Calculate the complex conjugate transpose of a matrix
2) Compare two matrices element-wise and find values greater than 1
3) Extract the diagonal and superdiagonal elements of a matrix
4) Remove zero elements from a vector
5) Plot a sine function with given inputs
6) Add text to a plot at a given position
7) Define and plot a custom function
8) Calculate statistics of a matrix
9) Sort a matrix in ascending and descending order
10) Find the zero of a custom function
QUESTION: 5 Run the MATLAB code: x = [1/4 1 sqrt(2) .3]; y = sin(x); plot(y) >> x = [1/4 sqrt(2) 3] x = 0.2500 1.4142 3.0000 >> y = sin(x) y = 0.2474 0.9878 0.1411 >> plot(y)
QUESTION: 7 The MATLAB code text(x,y,'alpha') Places the letter alpha at position (x, y). Write the text \Graph of e-xsin 'at (.5, .2) >> x=0:pi/40:2*pi; >> y=sin(x); >> plot(x,y) >> text(0.5,0.2,'graph of e^{-x}sin\phi')
function [s] = sinm(x) s=sin(x)-2.*x+2; end On command window >> sinm_2(0:2*pi/40:2*pi); >> fplot('sinm_2',[-10 10]) >> grid on >> title('the function sin(x)-2.*x+2') >> xzero=fzero('sinm_2',2)
xzero =
1.4987
QUESTION: 15 Ans: >> %Dec2Bin will convert a number to binary equivalent >> a=dec2bin(34)
a =
100010 QUESTION: 16 Ans: function [] =etimef(~) tic num_length=1:100000; toc end
QUESTION: 17 Ans: >> c=0:20:100; >> %formula for changing degree Celsius into oF. >> F= (9/5)*c+32; >> e=c' e = 0 20 40 60 80 100
function [F,X] =temp(C) C=([0:20:100])'; X=9./5.*C+32; F=([X])'; fprintf(' C F\n'); fprintf(' (degree) (fahrenheight)\n'); fori=1:length(C); fprintf('%8g %16g\n', C(i),F(i)); end end
QUESTION: 18 . In Europe daylight time starts on the last Sunday of March and ends on the last Sunday of October. Write a function that determines whether a given day number is in the summertime period or in the wintertime period of the Daylight Saving Time
Ans: function [f]= q18(datetime) datetime= input('enter the date') [yr,mon,dom,hr]=datevec(datetime); dow=weekday(datetime)-1; f = 'day numer is in summer time'; if (mon>4 &mon<10), return; end; if (mon==4 &dom>7), return; end; if (mon==4 &dom<=7 &dow==0 &hr>=2), return; end; if (mon==4 &dom<=7 &dow>0 &dom>dow), return; end; if (mon==10 &dom<25), return; end; if (mon==10 &dom>=25 &dow==0 &hr<2), return; end; if (mon==10 &dom>=25 &dow>0 & dom-24-dow < 1), return; end; f ='day number is in winter time'; end
QUESTION: 21 Let be given the string `Need-to-split-this-string'. We want to break it into the -tive strings `Need', `to', `split', `this', and `string'. Solutions may be based on strtok and the much faster strread Ans: function [parts] =q21( ~ ) str='18c' splitstr='[c]'; parts=regexp(str,splitstr,'split'); end
QUESTION: 22 We have a string that looks like `18C'. How to keep only the number 18? Ans: function [Result,N] =q22(~) S='18c' N = sscanf(S, '%d') end
QUESTION: 23 We want to save a vector v=[1 2 3 4]; into a text file. How to that? Ans: V=[1 2 3 4] >> save textfile.m V_ascii %to save the file >>load textfile.m >>textfile textfile= 1 2 3 4 QUESTION: 24 Write a code that removes all 2's in a matrix A Ans: function [ new] = q24(matrix ) matrix=input('enter matrix') new=matrix(matrix==2); end OR >> A=[2 2 6;3 2 6;2 7 4]; >> A(A==2)=[]
A = 3 7 6 6 4 QUESTION: 25 How can I comment several lines at once in stead of typing the symbol % at the beginning of each line? Ans: >>if(0) I am a student. My name is Azeem. I want peace. end %The text between if(0) and end will become comments
QUESTION: 26 How can I find where the matrix A changes sign? >> A=[1 -6 -4;-7 8 3]; >> S=sign(A) S =
1 -1 -1 -1 1 1
QUESTION: 28 Given an array like [2; 8; 3; 30; 4; 50; 100; 200; 4; 80; 500]. I want to split it into three arrays with different ranges: [0-10), [10-100), and [100-1000).The above array should become 2; 8; 3; 4; 4 30; 50; 80 100; 200; 500 How to do this? Ans: function [split,b ] = q28(~) % Result should look like 1 2 3 4... % 8 9 % 16 17 18 a = [1 2 3 4 8 9 16 17 18]; b=a-(1:length(a)); b = [true; diff(b(:)) ~= 0; true]; split = mat2cell(a(:).', 1, diff(find(b))); [m , n , o]=split{:} end
QUESTION: 30 Is there a convenient way of listing the names of all *.m functions thatare called by a given *.m function? function [] =q30(n ) n=input('enetr the name of fuction whose subfuctions names you want to know=') help 'n' end
QUESTION: 31 How can one set the background of a figure view as white? Ans: function [] =q31(~) set(gca,'color','white') whitebg('white') end (OR) >>figure=figure(color,[1 1 1])
QUESTION: 32 How can one simulate a curve shaped like a heart by a spline function? Ans: function [] = q32(~) n=100; x=linspace(-3,3,n); y=linspace(-3,3,n); z=linspace(-3,3,n); [X,Y,Z]=ndgrid(x,y,z); F=((-(X.^2) .* (Z.^3) -(9/80).*(Y.^2).*(Z.^3)) + ((X.^2) + (9/4).* (Y.^2) + (Z.^2)-1).^3); isosurface(F,0) lightingphong caxis axis equal colormap('flag'); view([55 34]) end
QUESTION: 37 I want to index the entries in a matrix by using vectors with row and column indices. How to do that? Ans: function [ out_args ] =q37( in_args) q=magic(4) q = [16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1]
function [ output_args ] =q38( input_args ) k=10 disp(fprintf('this is the number=%d',k)) end
QUESTION: 39 . I want to display variable values inside a disp command: \This is number: k". How to do that? Ans: >> line([1,1],[2,0],'marker','*','color','r','linestyle',':') >> clf >> line([1,1],[2,0],'marker','*','color','r','linestyle',':') >> line([3,1],[2,4],'marker','+','color','g','linestyle','--') >> line([2,2],[3,4],'marker','>','color','b','linestyle','-') >> axis([-5 5 -5 5])
QUESTION: 41 function [ output_args ] =q41( input_args ) x1=-3:.2:3; x2=-3:.2:3; [X,Y] = meshgrid(x1,x2); f = (X-3).^2 + (Y-3).^2; g = 10.*(X + Y); ix = g >= 4; f(ix)=200; surf(X,Y,f) grid on end
QUESTION: 42 How do I create a maximized figure window? function [ output_args ] =q42( input_args ) gcf = q41 set(gcf,'Units','normalized','Position',[0.00 0.034 1.00 0.905]) end (OR) >>h=figure; >>pause (0.1) >>Jf=get(h,javaframe); >>set(Jf, maximized ,1);
QUESTION: 43 I have to plot a variable number of data sets on the same graph with different symbols. How can I specify the symbols I want to use? How can I specify the order and color of the symbols to be used?
function [ output_args ] = q43( input_args ) xlabel({'x red';'x1 green'}) ylabel({'y red';'y1 green'}) end
QUESTION: 44
function [ output_args ] = q44( input_args ) p=[-100:100]; q=1:sum(p>=1)
p(q) end QUESTION: 45
function [ ] = q45(~) x=-1:.1:1; y=x; [xx,yy]=meshgrid(x,y); zz=(16-xx.^2).^(1/2); mesh(xx,yy,zz) title('The graph of z=(16-x^2)^(1/2)') xlabel('x-axis') ylabel('y-axis') zlabel('z-axis') axis tight end
QUESTION: 46 I have a char array '000101'. Is there any way to split this into six separate elements: '0' '0' '0' '1' '0' '1'? function [parts] =q46( ~ ) str='0 0 0 1 0 1' splitstr=[' ']; parts=regexp(str,splitstr,'split'); end
QUESTION: 47 How can I store strings of variable length? [Hint use cell arrays] function [ output_args ] = q47( input_args ) userinput={'AJ48 NOT'; 'AH43 MANA'; 'AS33 NEWEF'}; disp(userinput{1}); end
QUESTION: 48 function [ output_args ] =q48( input_args ) fid = fopen('use.m', 'r') x = fread(fid,inf) end
QUESTION: 65 function [ output_args ] =q65( input_args ) c={'Bob', 'Mary', 'Fred','Ken'} s = fprintf(' %s %s \n' , c{1} ,c{3} ); end
QUESTION: 66 function [ output_args ] = q66( input_args ) %calllib('libname', 'funcname', arg1, ..., argN) loadlibrary('MatlabGenericDll','GenericDll.h') calllib('MatlabGenericDll', 'FormatDrive') unloadlibraryMatlabGenericDll end
QUESTION: 67 Solve the equation ax2+ bx + c = 0 symbolically for x, and next for b. unction [ output_args ] = q67( input_args ) syms x a b c solve('a * x ^ 2 + b * x + c=0','x') solve('a * x ^ 2 + b * x + c=0','b') end
QUESTION: 68 . Solve the equation [cos (2x) + sin(x) - 1 = 0 ]symbolically. Next use ezplot to verify the result function [ output_args ] = q68( input_args ) syms x solve('cos(2*x) + sin(x) - 1 = 0','x') ezplot('cos(2*x)', -2, 3)
hold on ezplot('1-sin(x)', -2, 3) xlabel('cos(2*x)') hold off end
QUESTION: 69 Solve the equation tan(x) + sin(x) - 2 = 0 symbolically. Next, determine the numerical values of the roots. >>syms x >>f=tan(x)=sin(x)-2 >>solve(f); >>sol=sub(f,x,1.5) Sol= 2.168
(OR)
function [ output_args ] = q69( input_args ) %You can find this solution by calling the MuPAD numeric solver directly and specifying the interval where this solution can be found. To call MuPAD commands from the MATLAB Command Window, use the evalin or feval function solve('tan(x)+sin(x)-2=0','x') evalin(symengine, 'numeric::solve(tan(x)+sin(x)-2, x = 0..4)') end