How can I create a multiple fill with different colors using loops for an arbitrary vector
7 ビュー (過去 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!