How can i process the elements of a vector in this way

6 views (last 30 days)
Hello everyone
I have this vector
v=[-0.5 -0.3 0 1.2 1.3 1.7 -0.4 -0.6 0 0.9 0.2 0.5 -1.2 -2.3 3.2 0 -1.0 0 -5.5 -5.2 -6.4]
i want to divide the elements of this vector both between positive and negative (I want to neglect the zeros of the vector) and according to how many times they appear consecutively (that is according to the length of the sequences they appear). I mean, if i consider the negative values, i want to obtain
value_negative(1)=[-1.0]
value_negative(2)=[-0.5 -0.3; -0.4 -0.6; -1.2 -2.3]
value_negative(3)=[-5.5 -5.2 -6.4]
With "value_negative(n)" i indicate the negative elements of the vector that appear in a sequence of length n. If a sequence of negative values appear more that once, i want to obtain a matrix like in the case of value_negative(2).
Could you help me?
Thank you

Answers (1)

Rik
Rik on 18 Mar 2021
A good first start would be to split your vector into a cell array. I suspect you will need diff, find, sign, and mat2cell.
Then you can use cellfun to find the number of elements in each section. You can decide to remove the zeros at this stage, or to remove them before you convert to a cell array. I would suggest removing them afterwards to keep your code more understandable.
Once you have the length, you can merge them with a loop and cat.
Let me know if you have any issues in implementing this.
  4 Comments
salvatore vergine
salvatore vergine on 18 Mar 2021
I read all the documentation of the functions but I am not so good in matlab so I don't understand the logical process to follow. I have never used most of these functions.
Rik
Rik on 18 Mar 2021
Let's try the splitting first. The general idea is to find the run length of each type (pos/neg/0). That way we can use that in mat2cell to split the vector into a cell array.
The first step is to convert your array to the same values, so all negative numbers are the same, all positive numbers are the same, and all zeros are the same. We can use the sign function to do this.
Next, we need to find all positions where type (pos/neg/0) changes. We can use the diff function. (Note that this will reduce the length of the vector by 1, so we will need to be wary of that.) For every position where the type changes the result will be non-zero.
That leads us to the next step: find will return the indices of the positions with non-zero elements.
Those indices are very helpful, but don't yet tell us the length of each section. Which function do you think we need again?
Once we have the length of each section, we can use that and the original vector as inputs to the mat2cell function.
Can you try implementing these steps?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!