How to write a function.

4 vues (au cours des 30 derniers jours)
Peyton
Peyton le 17 Nov 2024
Commenté : Walter Roberson le 17 Nov 2024
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 commentaires
Peyton
Peyton le 17 Nov 2024
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 le 17 Nov 2024
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.

Connectez-vous pour commenter.

Réponses (1)

Madheswaran
Madheswaran le 17 Nov 2024
Modifié(e) : Madheswaran le 17 Nov 2024
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!

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by