How to write a function.
Show older comments
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 Comments
Peyton
on 17 Nov 2024
Walter Roberson
on 17 Nov 2024
You describe hw4_problem1 but you post code for hw4_problem5
Peyton
on 17 Nov 2024
Walter Roberson
on 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.
Answers (1)
Madheswaran
on 17 Nov 2024
Edited: Madheswaran
on 17 Nov 2024
0 votes
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:
- Note the input argument for the 'isprime' function - https://mathworks.com/help/matlab/ref/isprime.html
- Learn what logical indexing is - https://mathworks.com/matlabcentral/answers/422002
Here is where you can learn more about MATLAB: https://matlabacademy.mathworks.com/details/matlab-onramp/gettingstarted
Hope this helps!
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!