splitting a vector into separate vectors
显示 更早的评论
Hi Matlab community,
I have a vector like
V = [2 2 2 2 2 4 4 4 7 7 8 9]
I want to separate this vector into
V1 = [2 2 2 2 2 ], V2=[4 4 4 ], V3=[7 7 ], V4=8, V5=9
Suppose that I do not know the value in vector V. In each iteration, I have a new vector.
Thanks
采纳的回答
更多回答(2 个)
Steven Lord
2024-9-30
1 个投票
Can you dynamically create variables with numbered names like V1, V2, V3, etc.? Yes.
Should you do this? The general consensus is no. That Discussions post explains why this is generally discouraged and offers several alternative approaches.
If you are working with large 1D vectors. using a binary search might be a good option to optimize time complexity.
Below is the sample code:
function separatedVectors = separateUsingBinarySearch(V)
% Initialize an empty cell array to store the separated vectors
separatedVectors = {};
n = length(V);
if n == 0
return;
end
startIdx = 1;
% Continue until the start index exceeds the length of the vector
while startIdx <= n
value = V(startIdx);
endIdx = findEndIndex(V, startIdx, n, value);
% Store the current group of identical elements in the cell array
separatedVectors{end+1} = V(startIdx:endIdx);
startIdx = endIdx + 1;
end
end
function endIdx = findEndIndex(V, startIdx, n, value)
low = startIdx;
high = n;
% Perform binary search to find the last occurrence of 'value'
while low < high
mid = floor((low + high + 1) / 2);
if V(mid) == value
low = mid; % Move the lower bound up if the mid value matches
else
high = mid - 1; % Move the upper bound down if the mid value does not match
end
end
endIdx = low;
end
% Example usage
V = [2 2 2 2 2 4 4 4 7 7 8 9 9 9 9];
separatedVectors = separateUsingBinarySearch(V);
% Display the results
for i = 1:length(separatedVectors)
fprintf('[%s]\n', num2str(separatedVectors{i}));
end
The function separateUsingBinarySearch efficiently divides a sorted vector V into sub-vectors, each containing consecutive identical elements. For each starting index, findEndIndex uses binary search to find the last occurrence of the current value efficiently. The sub-vector from startIdx to endIdx is extracted and added to separatedVectors. The process repeats by updating startIdx to just after endIdx for the next group.
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!