例1.
Problem 8. Add two numbers
Given a and b, return the sum a+b in c
function c = sum_of_a_and_b(a, b)
c = a + b;
end
result = sum_of_a_and_b(3, 4); % Example usage
disp(result); % Display the result
例2.
Problem 3. Find the sum of all the numbers of the input vector
Find the sum of all the numbers of the input vector x.
Examples: Input x = [1 2 3 5] Output y is 11Input x = [42 -1] Output y is 41
function sum_x = sum_of_vector(x)
% 计算输入向量 x 中所有数字的总和
sum_x = sum(x);
% 打印输出结果
fprintf('Input x = %s\nOutput y is %d\n', mat2str(x), sum_x);
end
% 示例
x1 = [1 2 3 5];
sum_of_vector(x1);
x2 = [42 -1];
sum_of_vector(x2);
例3
Problem 1702. Maximum value in a matrix
Find the maximum value in the given matrix.
For example, if
A = [1 2 3; 4 7 8; 0 9 1];
then the answer is 9.
function max_value = find_max_in_matrix(A)
% 在给定矩阵中找到最大值
max_value = max(A, [], 'all');
% 打印输出结果
fprintf('The maximum value in the matrix is: %d\n', max_value);
end
% 示例
A = [1 2 3; 4 7 8; 0 9 1];
find_max_in_matrix(A);
例4.
Problem 1545. Return area of square
Side of square=input=a
Area=output=b
function b = square_area(a)
% 计算正方形的面积
b = a^2;
end
例5.
Problem 23. Finding Perfect Squares
Given a vector of numbers, return true if one of the numbers is a square of one of the numbers. Otherwise return false.
Example:
Input a = [2 3 4]
Output b is true
Output is true since 2^2 is 4 and both 2 and 4 appear on the list.
判断给定的数字向量中是否存在某个数字的平方等于该向量中的另一个数字:
function b = has_square_number(a)
% 判断向量中是否存在数字的平方等于向量中的另一个数字
n = length(a); % 获取向量的长度
b = false; % 初始化输出为 false
for i = 1:n
for j = 1:n
if i ~= j && a(j) == a(i)^2 % 如果存在数字的平方等于向量中的另一个数字
b = true; % 更新输出为 true
return; % 结束循环
end
end
end
end
可以调用这个函数并传入数字向量 a,它会返回 true 如果向量中存在数字的平方等于向量中的另一个数字,否则返回 false。
例6.
Problem 2. Make the vector [1 2 3 4 5 6 7 8 9 10]
In MATLAB, you create a vector by enclosing the elements in square brackets like so:
x = [1 2 3 4]Commas are optional, so you can also type
x = [1, 2, 3, 4]Create the vector
x = [1 2 3 4 5 6 7 8 9 10]There's a faster way to do it using MATLAB's colon notation.
(“使用MATLAB的冒号表示法可以更快地完成。”)
x = 1:10;
例7
Problem 1035. Generate a vector like 1,2,2,3,3,3,4,4,4,4
Generate a vector like 1,2,2,3,3,3,4,4,4,4
So if n = 3, then return
[1 2 2 3 3 3]
And if n = 5, then return
[1 2 2 3 3 3 4 4 4 4 5 5 5 5 5]
u = repelem(v,n) 返回一个重复 v 中元素的向量,其中 v 是一个标量或向量。
- 如果 n 是一个标量,则 v 的每个元素都重复 n 次。u 的长度为 length(v)*n。
- 如果 n 为向量,则它必须与 v 具有相同的长度。n 的每个元素指定重复 v 对应元素的次数。
————————————————
原文链接:https://blog.youkuaiyun.com/jk_101/article/details/110949858
function result = generate_vector(n)
% Generate values from 1 to n
values = 1:n;
% Repeat each value i times where i ranges from 1 to n
result = repelem(values, 1:n);
end
You can then cal

这篇博客介绍了MATLAB中的多个问题及其解决方案,包括加法运算、向量求和、查找完美平方、创建特定向量、计算三角数、求斜边长度、选取向量间隔元素、反转向量、移除矩阵列、交换输入参数、检查数字在向量中是否存在、判断向量单调性、获取向量满足条件的索引、创建乘法表、返回字符数组首尾字符、计数二进制字符串中的1、模拟掷骰子、生成随机不重复向量以及计算幻方的幻数等操作。
最低0.47元/天 解锁文章
1275

被折叠的 条评论
为什么被折叠?



