Need help writing a matlab function.

6 views (last 30 days)
Peyton
Peyton on 17 Nov 2024
Answered: Walter Roberson on 17 Nov 2024
Write a function called hw4_problem3 that takes a vector containing integers called w
and a scalar, n, as its input arguments. The function returns the first element found in w that are
larger than or equal to n. If there is no element in w that is larger than or equal to n, return -1.
  3 Comments
Peyton
Peyton on 17 Nov 2024
Can i just get an answer because i got this far
function output = hw4_problem1(A)
% Check if the input A is a numeric matrix
if ~isnumeric([1, 2, 3; 4, 5, 6])
error('Input A must be a numeric matrix.');
end
% Check if the matrix A is empty
if isempty([1, 2, 3; 4, 5, 6])
error('Input A cannot be empty.');
end
% Get the number of rows and columns of A
[numRows, numCols] = size([1, 2, 3; 4, 5, 6]);
% 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
Peyton
Peyton on 17 Nov 2024
cause i keep getting an error

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 17 Nov 2024
Replace all your [1, 2, 3; 4, 5, 6] by A.
Replace
output = hw4_problem1(A)
by
output = hw4_problem1(A, n)
A is a vector, not a matrix so don't overcomplicate it by worrying about rows and columns.
Hint: Use find. For example
A = [1,4,9,2,4,0,8,-20]
A = 1×8
1 4 9 2 4 0 8 -20
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
firstIndex = find(A >= 3, 1, 'first')
firstIndex = 2
value = A(firstIndex) % Get first value more than n
value = 4
Please adapt this to your homework problem.

Walter Roberson
Walter Roberson on 17 Nov 2024
A deliberately clumsy implementation:
function appropriate_element_to_return = hw4_problem3(w, n)
array_being_indexed = w;
value_to_compare_to = n;
found_it_at_location = nan;
for index_of_array = numel(w):-1:1
if array_being_indexed(index_of_array) >= value_to_compare_to
found_it_at_location = index_of_array;
end
end
if ~isfinite(found_it_at_location)
appropriate_element_to_return = -1;
else
appropriate_element_to_return = array_being_indexed(found_it_at_location);
end
end

Categories

Find more on Get Started with MATLAB 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!