How can I create a multiple fill with different colors using loops for an arbitrary vector
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Lewis Asilevi
am 12 Jan. 2018
Beantwortet: Lewis Asilevi
am 13 Jan. 2018
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 Kommentare
Akzeptierte Antwort
Weitere Antworten (1)
Guillaume
am 12 Jan. 2018
Bearbeitet: Guillaume
am 12 Jan. 2018
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 Kommentare
Guillaume
am 12 Jan. 2018
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.
Siehe auch
Kategorien
Mehr zu Blue finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
