disp('newNums1='); disp(newNums1);
x2=find(mod(find(nums2),2)==1);%向量2 [values2]=nums2(x2); newNums2=values2; disp('nums2='); disp(nums2); disp('newNums2='); disp(newNums2);
x3=find(mod(find(nums3),2)==1);%向量3 [values3]=nums3(x3); newNums3=values3; disp('nums3='); disp(nums3); disp('newNums3='); disp(newNums3);
Matlab第四章
1. 有如下数据:
X y 1 1.00000 1.1 1.23368 1.2 1.55271 1.3 1.99372 1.4 2.61170
利用本章介绍的几种插值方法对其进行插值,得到每隔0.05的结果。
%4种插值方法
x=[1 1.1 1.2 1.3 1.4]; %x与y的值 y=[1.00000 1.23368 1.55271 1.99372 2.61170]; length_of_x=length(x);
scalar_x=[x(1):0.05:x(length_of_x)]; length_of_sx=length(scalar_x);
for i=1:length_of_sx 法
y_nearest(i)=interp1(x,y,scalar_x(i),'nearest'); y_liner(i)=interp1(x,y,scalar_x(i),'liner'); y_spline(i)=interp1(x,y,scalar_x(i),'spline'); y_cubic(i)=interp1(x,y,scalar_x(i),'cubic'); end
subplot(2,2,1),plot(x,y,'*'),hold
on,plot(scalar_x,y_nearest),title('nearest'); subplot(2,2,2),plot(x,y,'*'),hold
on,plot(scalar_x,y_liner),title('linear'); subplot(2,2,3),plot(x,y,'*'),hold
on,plot(scalar_x,y_spline),title('spline'); subplot(2,2,4),plot(x,y,'*'),hold
on,plot(scalar_x,y_cubic),title('cubic');
%定义4种方%输出
2. 2. 求下列函数的解,并绘制图形。 (1) y=ex-x5,初始点为x=8. (2) y=xsin(x)
>> y=@(x)exp(x)-x^5; >> x=fzero(y,8) x =
12.7132
>> fplot(y,[10,14]); >> hold on
>> plot(x,y(x),'r*') >>y=@(x)x*sin(x); >> x=fzero(y,0) x = 0
3.求下列函数的极值。 (1) z=x2-(y-1)2 (2) z=(x-y+1)2
>> z=@(x)x(1)^2-(x(2)-1)^2;
>> [x,fvalue]=fminsearch(z,[-1,1])
Exiting: Maximum number of function evaluations has been exceeded - increase MaxFunEvals option. Current function value:
-29278786696692084000000000000000000000000000000000000000000000000000000000000000000000.000000 x =
1.0e+043 *
1.1138 1.2383 fvalue =
-2.9279e+085
>> z = @(x)(x(1)-x(2)+1)^2; >> [x,fvalue]=fminsearch(z,[-1,1]) x =
-1.2073 -0.2073 fvalue =
1.9045e-022
4.计算下列积分。 (1)
(2)
>> f = @(x)x+x.^3+x.^5; >> q = quad(f,-1,1) q =
2.2204e-016
>> f= @(x,y)sin(y).*(x+y)./(x.^2+4); >> q = dblquad(f,1,10,1,10) q =
5.5254
Matlab第五章
1.编制一个脚本,查找给定字符串中指定字符出现的次数和位置.
%查找给定字符串中指定字符出现的次数和位置
letter='a'; %指定字符 string='I have a long string'; %给定字符串 places=findstr(string,letter); %位置 times=length(places); %次数 disp('places are :'); disp(places); disp('times are :'); disp(times);
2.编写一个脚本,判断输入字符串中每个单词的首字母是否为大写,若不是则将其修改为大写,其他字母为小写.
%将每个单词首字母变为大写
str = 'I have a long string'; disp(str);
nlength = length(str); for k=1:nlength
if (k==1 || isspace(str(k-1))) && (str(k)<='z' && str(k)>='a') str(k) = char(double(str(k)) - 32); end end disp(str);
3.创建 2×2 单元数组,第 1、2 个元素为字符串,第三个元素为整型变量,第四个元素为双精度(double)类型,并将其用图形表示.
>> A=cell(2,2) A =
[] [] [] []
>> A(1,1)={'string1'}; >> A(1,2)={'string2'}; >> A(2,1)={uint8(100)}; >> A(2,2)={double(60)};