How to write a function.

45 次查看(过去 30 天)
Peyton
Peyton 2024-11-17,3:56
评论: Walter Roberson 2024-11-17,6:32
Write a function called hw4_problem1 takes an at most two-dimensional matrix A as
its only input. The function returns a row vector v containing all elements of A that are prime
numbers. The elements of v are stored according to row-major ordering of A, which means you have
to check the elements in A row by row. You are allowed to use the isprime built-in function.
Hint: You can initialize the output v with an empty matrix before starting a loop, i.e., v = [];. As
you want to add more values to v, you can use end+1 as the new index in v. For example, if you
want to add a value 10 to the empty v, you can write v(end+1) = 10;. The variable v now has
one value, v(1) = 10;
Example run on Command Window:
>> v = hw4_problem1([ 38 83 24 54 6; 89 8 27 28 23])
v =
83 89 23
  4 个评论
Peyton
Peyton 2024-11-17,4:11
i did lol im so tired but here is the correct one
function output = hw4_problem1(A, n)
% Check if the input A is a numeric matrix
if ~isnumeric(A)
error('Input A must be a numeric matrix.');
end
% Check if the matrix A is empty
if isempty(A)
error('Input A cannot be empty.');
end
% Get the number of rows and columns of A
[numRows, numCols] = size(A);
% Output matrix for storing results (just as an example here)
output = zeros(numRows, numCols);
% Loop over the rows of A
for i = 1:numRows
for j = 1:numCols
% Example operation: simply copy the elements of A to output
output(i = 1:numRows, j = 1:numCols) = A(2,2);
end
end
end
Walter Roberson
Walter Roberson 2024-11-17,6:32
output(i = 1:numRows, j = 1:numCols) = A(2,2);
In MATLAB, that would be equivalent to
output("i", 1:numRows, "j", 1:numCols) = A(2,2);
which would fail because strings such as "i" cannot be used as indexes into arrays.

请先登录,再进行评论。

回答(1 个)

Madheswaran
Madheswaran 2024-11-17,6:22
编辑:Madheswaran 2024-11-17,6:25
Hi @Peyton, This seems like a homework question, so I will give you a headstart, from which you can pick up. Learn how to write and call functions from here: https://mathworks.com/help/matlab/functions.html
Then, go through the following documentation and work on how to apply it to your question:
  1. Note the input argument for the 'isprime' function - https://mathworks.com/help/matlab/ref/isprime.html
  2. Learn what logical indexing is - https://mathworks.com/matlabcentral/answers/422002
Hope this helps!

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by