How can I create a multiple fill with different colors using loops for an arbitrary vector
조회 수: 4 (최근 30일)
이전 댓글 표시
Hi all, I am not very advance in matlab so forgive me if I mix up the terms. I understand the basics of how to use the fill function fill(X,Y,C). From matlab documentation, it can also be used for multiple fills say fill(X1,Y1,C1,X2,Y2,C2,...).
I have a vector
X = [1 2 2 2 4 4 5 5 3 3 3 1 1 1]
and
Y = [0 1 1 0 0]
Nz = linspace(0,1,length(X))
dz = max(Nz)/length(X)
I want to write a for loop to create a multiple fill for each identical successive element with different colors for example
x1 = [0 dz*count dz*count 0 0]
Y = [0 1 1 0 0]
x2 = [dz*count dz*count2 dz*count2 dz*count dz*count]...
Y = [0 1 1 0 0]
C1,C2...
fill(x1,Y,C1,x2,Y,C2...).
"count" here determines the number of times successive elements occur in the vector. "dz" is the step size. I would be glad if anyone here can assist. Thank you.
댓글 수: 3
채택된 답변
추가 답변 (1개)
Guillaume
2018년 1월 12일
편집: Guillaume
2018년 1월 12일
As suspected a loop is not required:
X = [1 2 2 2 4 4 5 5 3 3 3 1 1 1];
seqlengths = diff([0, find(diff(X)), numel(X)]); %calculate the length of each continuous sequence
colour = X(cumsum(seqlengths)); %extract the colour corresponding to each sequence
xpoints = repelem(cumsum([0 seqlengths(1:end-1); seqlengths], 2), 2, 1); %build xpoints matrix
ypoints = [0 1 1 0].';
fill(xpoints, ypoints, colour);
But as pointed out by Stephen, using image is even simpler.
댓글 수: 3
Guillaume
2018년 1월 12일
The colour parameter is unchanged from your original code. It is an index into the colour map. You can use any colour map you wish.
You can multiply the xpoints coordinates by any factor you want.
xpoints = xpoints / numel(X) %to scale x axis to [0 1]
In order to understand better the code I've written, I would recommend you break it down and see what each function does. For example
- diff(X) calculates the difference between consecutive elements of X. It's therefore going to be 0 for consecutive identical elements and non-zero otherwise.
- find(diff(X)) thus returns the indices at which the X values change
- the diff of that is thus the length of each sequence
- etc.
참고 항목
카테고리
Help Center 및 File Exchange에서 Blue에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
