A for loop that counts the negatives of a 1D array
5 ビュー (過去 30 日間)
古いコメントを表示
My function is to recieve a 1D array of numbers as the input and uses a for loop to find the location of all negatives in the array and return it as the output. If given [-2 3 0 -5 4] the output would be [1 4]. I'm not sure what to do in order for it to count, does y have to be a array before the for loop? If so, how do I add my indexing variable to y inside the for loop?
function y = WhereNeg(x)
[xrow, xcol] = size(x);
for ii = 1:xcol
if x(ii) < 0
y = ii;
end
end
3 件のコメント
Riccardo Scorretti
2022 年 4 月 19 日
Dear Eric, this look like an assigment (= you have to do, not us) so I'll give you some hints, but not the solution.
- your function accepts as input argument a vector, and it is expected to return a vector: in your code, it returns a scalar (because of the line y = ii). A possible, but very inefficient way to fix it, would be to define y as an empty vector before entering the loop, and then to put new values (= ii) at the end of y. Remember that you can access to the last element of a vector by using the syntax y(end), so y(end+1) would be the next unoccupied position. I would like to stress that this is a very inefficient way to do.
- In Matlab, normally this kind of job can be done in a single line by using the function find (read the doc). Your program is written in a kind of C style.
- I strongly suggest you to use numel to get the number of elements of a vector, not size. The point is that your code assumes that x is a row-vector, which is an unnecessary hypothesis.
- It is a good practice (at least, I consider that it is) to close all functions by end, so I advice you to add an ending keyword end to close your function.
回答 (1 件)
Vatsal
2023 年 11 月 17 日
Hi,
In your current function, the variable 'y' is being overwritten each time a negative number is found. To store all the indices of negative numbers, you should initialize 'y' as an empty array before the loop and then append to it each time a negative number is found.
Here's how you can modify your function:
function y = WhereNeg(x)
y = []; % Initialize y as an empty array
[xrow, xcol] = size(x);
for ii = 1:xcol
if x(ii) < 0
y = [y ii]; % Append the index to y
end
end
end
In this modified function, 'y' is an array that gets populated with the indices of negative numbers in 'x'. The line ‘y = [y ii]’ appends the current index 'ii' to the array 'y' when a negative number is found. To count the number of negative numbers, you can simply use the above code and return the length of 'y'.
I hope this helps!
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!