How to write a function.

조회 수: 46 (최근 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