Need help writing a matlab function.

28 ビュー (過去 30 日間)
Peyton
Peyton 2024 年 11 月 17 日 2:47
回答済み: Walter Roberson 2024 年 11 月 17 日 3:27
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 件のコメント
Peyton
Peyton 2024 年 11 月 17 日 3:10
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 2024 年 11 月 17 日 3:13
cause i keep getting an error

サインインしてコメントする。

回答 (2 件)

Image Analyst
Image Analyst 2024 年 11 月 17 日 3:17
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 2024 年 11 月 17 日 3:27
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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by