Question
Hi there, my question could easily be solved with a simple loop but I'm curious if there is a nice genuine matlab way of doing this: I have a vector "v1" containing 10 entries. First 5 belong together, next 2 belong together and the last 3 again (somehow). So I got a vector "v2" with v2 = [5; 2; 3]; I want now something like v3 = [1 1 1 1 1 2 2 3 3 3]; So I could access my v1 vector with: v1(v3==1); (Background for the question are different colors for each group with the plot-command.) Thanks already in advance - I'm sure Matlab holds a nice and short way of doing this :-)
Related Questions
Expert Answer
Kshitij Singh
PhD Expert
Answered Nov 20, 2025
c=cumsum(v2); v3=zeros(1,c(end)); v3([1,c(1:end-1)])=1; v3=cumsum(v3); v3(end)=[],
Summary:
-
The
cumsum(v2)creates a cumulative sum vectorc. -
A zero vector
v3is created with a length of the last value inc. -
Positions in
v3at1andc(1:end-1)are set to 1. -
Another cumulative sum is calculated over this
v3. -
The last element of
v3is removed.
The result is a vector v3 that mirrors the cumulative structure of v2 but adjusted for the specific indexing manipulation.
This process transforms a cumulative indexing approach into a sequential one, useful in various signal processing or data transformation scenarios.
Have a different question? Ask here