How can I make a function to sum vector elements between various values?
Show older comments
I'm trying to use a function to count how many elements of a vector fall within certain thresholds. For example, if A={1 3 4 5 7 8 9 9 7} I want to find and sum vectors between <3, <6, <10, and display them in an array. Answer would be: Ans = {1 3 5}
So far, I have:
function output=Thresh4(N)
A={0 0 0};
if A <3
count A(1)
else if < 6
count A(2)
else A<10
count A(3)
end
It seems like it isn't running through the selected vector, and therefore not displaying results?
3 Comments
David Fletcher
on 18 Apr 2018
Edited: David Fletcher
on 18 Apr 2018
Do you really need a cell array? Easier to make A a vector and just use logical indexing to extract the elements based on a condition i.e.
A=[1 3 4 5 7 8 9 9 7]
lessThan3=A(A<3)
It can still be done with a cell array, but everything ends up being a bit more effort with cell arrays.
Stephen23
on 18 Apr 2018
@ Bob Graham: is there a special reason why you are using a cell array to store scalar numeric data? Processing numeric data is much simpler using numeric arrays.
Bob Graham
on 18 Apr 2018
Edited: Bob Graham
on 18 Apr 2018
Answers (1)
This is much simpler if you do not use cell arrays:
>> V = [1 3 4 5 7 8 9 9 7]; >> nnz(V<3) ans = 1 >> nnz(3<=V & V<6) ans = 3 >> nnz(6<=V & V<10) ans = 5
Note that you could also use the inbuilt histogram functions, e.g. histc:
>> cnt = histc(V,[0,3,6,10]) cnt = 1 3 5 0
2 Comments
Bob Graham
on 18 Apr 2018
function output = Thresharray(A)
but nowhere inside the function do you define what output actually is. Also you define one input argument A, but nowhere inside the function do you use it (so your input is totally ignored). Inside the function you refer to a variable V, but it is not defined anywhere (so will throw an error). Perhaps you meant to do this:
output = histc(A,[0,50,75,100]);
Also your function call again defines the data as a cell array:
Thresharray({44 55 77 99})
None of the code I showed you works with cell arrays. While it is possible to do what you want for a cell array it would be pointlessly complex, and in my opinion a waste of time. You should be using a numeric array for storing numeric data:
Thresharray([44,55,77,99])
You should revise the basic data classes in MATLAB (e.g. numeric array, cell arrays, etc):
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!