create multiple figures of patches with random colors

3 vues (au cours des 30 derniers jours)
Declan Bourke
Declan Bourke le 27 Juin 2016
Commenté : Lina KORONFEL le 7 Juil 2020
I'm trying to create a number of patches with different colors using a random number function and all of the regular colors in MATLAB (i.e. g,r,b etc). I'm using a 'for' loop and assigning a new color to the patch each time but for some reason the script returns patches with the same color every time. The section of scripts i'm using now is:
for i=1:12
figure
col_list='ymcrgbk';
col=randi([1,7],1);
random_color=col_list(col);
patch_x=[0 2 2 0]
patch_y=[0 0 2 2]
final_color=['-' random_color]
patch(patch_x,patch_y,'final_color');
end
  2 commentaires
Stephen23
Stephen23 le 27 Juin 2016
Modifié(e) : Stephen23 le 27 Juin 2016
Note that operations which do not depend on the loop variable should be moved outside of the loop. For example it would be much more efficient to call randi just once before the loop rather than multiple times inside the loop.
Also note that using i or j as the loop variable is not recommended as it is the name of the inbuilt imaginary unit.
See my answer for a more efficient way of writing a loop like this.
Declan Bourke
Declan Bourke le 27 Juin 2016
That's great, i will make a note for the future and stop using i for the loop variable.
Thanks for the advice,
Declan

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 27 Juin 2016
Modifié(e) : Stephen23 le 27 Juin 2016
N = 12;
vec = 'ymcrgbk';
clr = vec(randi(numel(vec),N));
figure
for k = 1:N
X = [0,2,2,0]+k;
Y = [0,0,2,2];
patch(X,Y,clr(k));
end
  2 commentaires
Declan Bourke
Declan Bourke le 27 Juin 2016
tried it and worked. thanks for the help!
Lina KORONFEL
Lina KORONFEL le 7 Juil 2020
Thank you!

Connectez-vous pour commenter.

Plus de réponses (1)

KSSV
KSSV le 27 Juin 2016
clc; clear all ;
for i=1:12
figure
col_list='ymcrgbk';
col=randi([1,7],1);
random_color=col_list(col) ;
patch_x=[0 2 2 0] ;
patch_y=[0 0 2 2] ;
final_color=['-' random_color] ;
patch(patch_x,patch_y,random_color);
end
  1 commentaire
Declan Bourke
Declan Bourke le 27 Juin 2016
tried and worked. thanks for your help!

Connectez-vous pour commenter.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by