How to select values in a vector
70 次查看(过去 30 天)
显示 更早的评论
Hello,
My vector has sets of values every certain time (this time is variable) and I would like a new vector (with the same size as the 'posicaofinal' vector) with only the first two values of each set of values. For example: If I have 8 values, I only choose the first 2. If I have 1 value (this happens), I discard this value from the new array. Basically I'm just picking the first pairs of values.
Thanks in advance.
0 个评论
回答(1 个)
Sajid Afaque
2022-2-16
编辑:Sajid Afaque
2022-2-16
hello ,
as i have understood from your description i have framed a solution.
Yes for sure the below code can be optimised further, but ill leave this task for you.
Hope this helps
%make a copy of your data and work on that
copy_data = posicaofinal;
count = 1; % number of successive non adjacent number you need, here you need two non zero numbers from a group
for i = 1 : 1 : numel(copy_data)
if copy_data(i) == 0
count = 1;
continue;
else
%check whether the adjacent values of the current data are 0 i.e.
%this group has only one non zero value
if i == 1
singularity_condition = (copy_data(i+1) == 0);
elseif i == numel(copy_data)
singularity_condition = (copy_data(i-1) == 0);
else
singularity_condition = (copy_data(i+1) == 0 && copy_data(i-1) == 0);
end
%below code discards single non zero value and if there are group
%of non zeroes together , then replace all the values of the group
%except for starting two values
if singularity_condition
copy_data(i) = 0;
else
if count < 3
count = count+1;
continue;
else
copy_data(i) = 0;
end
end
end
end
%copy_data is your new data with same length as posicaofinal
2 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Scope Variables and Generate Names 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!