matlab cody学习笔记 day13

感觉现在的题目越来越难了,好想每日鸡汤激励一下自己好好学习,不要怕!

(1)Which values occur exactly three times?
Return a list of all values (sorted smallest to largest) that appear exactly three times in the input vector x. So if
x = [1 2 5 2 2 7 8 3 3 1 3 8 8 8]
then
y = [2 3]
一些函数的学习:
C = unique(A):返回的是和A中一样的值,但是没有重复元素。产生的结果向量按升序排序。
n=hist(Y): 默认十个等间隔区间,并返回每个范围内的Y的元素个数作为一行向量;
[n,xout]=hist(Y,X):返回的参数中,n是每一个区间的个数,xout是区间的中心位置,输入参数中X是一个事先给定的区间划分,统计Y在X这个区间划分下的个数。
答:
function y = threeTimes(x)
[m,n] = hist(x,unique(x));
y = n(find(m == 3));
答:
function y = threeTimes(x)
count =0
y =[]
for i =1:length(x)
d =x-x(i)
for j =1:length(x)
if(d(j) == 0)
count =count+1
end
end
if(count ==3)
if(x(i)< 0)
y =[y,x(i)]
count =0
else
y =[y,x(i)]
count =0
end
end
count =0
end
y = unique(y)
end
用for和if去做,就很复杂,这里的unique只是排序。

(2)Return the largest number that is adjacent to a zero
This example comes from Steve Eddins’ blog: Learning Lessons from a One-Liner
Write a function that takes a list or array of numbers as input and return the largest number that is adjacent to a zero.
Example:
Input x = [1 5 3 0 2 7 0 8 9 1 0]
Output y is 8
This problem was originally posed by Greg Wilson of Software Carpentry.
第一反应是用find函数,寻找0所在的位置,然后把这些位置的坐标分别加一和减一,构成临近数字的新数组,进行大小判断,但是有一个问题是,0的位置可能在开头也可能在结尾,所以单纯的+1和-1是会出错的,所以需要先将输入的x数组扩充。
答:
x=[-inf,x,-inf];
a=x(find(x0)-1);
b=x(find(x
0)+1);
y=max([a,b]);
答:
y = [];
a=[];
k=1;
L=length(x);
for i=1:L
if x(i)0
if i
1
a(k)=x(i+1);
k=k+1;
elseif i==L
a(k)=x(i-1);
k=k+1;
else
a(k)=x(i-1);
a(k+1)=x(i+1);
k=k+2;
end
end
end
[y,index]=max(a);
end
不用find函数的运算速度就有些慢了。
(3)今天刷到的第三题比较简单。就不写了!

加油!今天要好好学习哦!

猜你喜欢

转载自blog.csdn.net/yxnooo1/article/details/114058016