matlab cody学习笔记 day7

(1)Problem 25. Remove any row in which a NaN appears
Given the matrix A, return B in which all the rows that have one or more NaNs have been removed. So for
A = [ 1 5 8
-3 NaN 14
0 6 NaN ];
then
B = [ 1 5 8 ]
答:
function B = remove_nan_rows(A)
A = A(all(A==A,2), : ) ;
A = A(~any(isnan(A),2), : ) ;
A(any(A~=A,2), : ) = [];
A(any(isnan(A),2), : ) = [];
B = A;
以上是知乎大神给的答案,上面四句话都可以实现该有的功能。
其中需要便捷使用的函数有:all,any
①matlab中all(x) 表示:
1)如果x是一个向量,则如果x的所有元素都不等于0,all(x)返回1,否则返回0.
2)如果x是一个矩阵,则沿着列的方向,判断x的每一列是否包含0元素。对于各列,如果不包含0元素,则返回1否则0。这样all(x)最终得到一个行向量,每个元素是都x的每一列的判断结果。类似地,如果想判断x的每一行是否不包含0元素,使用all(x,2),表示沿着x的第二个维度即行的方向判断。
②any(A)表示确定任何数组元素是否为非零。
1)B = any(A)
如果 A 为向量,当 A 的任何元素是非零数字或逻辑 1 (true) 时,B = any(A) 返回逻辑 1,当所有元素都为零时,返回逻辑 0 (false) 。
如果 A 为非空非向量矩阵,B = any(A) 将 A 的各列视为向量,返回包含逻辑 1 和 0 的行向量。
如果 A 为 0×0 空矩阵,any(A) 返回逻辑 0 (false)。
如果 A 为多维数组,则 any(A) 沿第一个非单一维度运算并返回逻辑值数组。此维的大小将变为 1,而所有其他维的大小保持不变。
2)B = any(A,dim)
沿着 dim 维测试元素。dim 输入是一个正整数标量。

(2)Problem 14. Find the numeric mean of the prime numbers in a matrix.寻找素数的平均数
There will always be at least one prime in the matrix.
Example:
Input in = [ 8 3
5 9 ]
Output out is 4 or (3+5)/2
答:
function out = meanOfPrimes(in)
B = isprime(in);
out = mean(in(B));
其中需要便捷使用的函数有: isprime查找素数的函数,可以减少判断素数进行循环相除的步骤。

(3)Who Has the Most Change?
You have a matrix for which each row is a person and the columns represent the number of quarters, nickels, dimes, and pennies that person has (in that order). What is the row index of the person with the most money?
Note for those unfamiliar with American coins: quarter = $0.25, dime = $0.10, nickel = $0.05, penny = $0.01.
Example:
Input a = [1 0 0 0; 0 1 0 0]
Output b = 1
since the first person will have $0.25 and the second person will have only $0.05.
答:
function b = most_change(a)
[m,n]=size(a);
B = ones(m,1);
for i = 1:m
B(i) = a(i,1)/4 + a(i,2)/20 + a(i,3)/10 + a(i,4)/100;
end
b = find(B == max(B));
原答案里有一个循环,想把这个循环去掉,考虑matlab数组运算的便捷性,改进为:
答:
d = [1/4 1/20 1/10 1/100];
[mm nn]=max(sum((a.*d)’));
b = nn;

(4)Reverse the vector反转数组
Reverse the vector elements.
Example:
Input x = [1,2,3,4,5,6,7,8,9]
Output y = [9,8,7,6,5,4,3,2,1]
答:
y = flip(x);
答:
for i=0:length(x)-1
y(1+i) = x(end-i);
end
答:
y=x(end: -1:1);
反转数组属于基本操作,还比较常用,在编程中第三种答案更为常用!

猜你喜欢

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