MATLAB bar() error: 'Unrecognized option "var" with custom variable names - matlab

I'm writing longer script for plotting some bar plots in Matlab. I want to set my own colors of the bars when a proper condition is met. I have 30 bars in one plot. That's the general background, I won't paste here this long code, instead of I created shorter code only to illustrate one particular problem I'm struggling with. For some reason bar() function in MATLAB doesn't allow to use custom variables to indicate which plot needs to be, for example in this case, re-colored.
Here's the sample script that I prepared:
cond_1 = 10;
cond_2 = 8;
i = 1;
cond_SD_1 = 2;
cond_SD_2 = 3;
z = [cond_1, cond_2];
zz = [cond_SD_1, cond_SD_2];
hold on
newName=sprintf('cond_%d',i);
title(newName);
bar(1, cond_1, 'FaceColor', 'Red','LineWidth',2)
bar(2, newName, 'FaceColor', 'Blue','LineWidth',2)
errorbar(z,zz,'color',[.44 .44 .44],'linestyle','none','linewidth',2), grid on, grid minor, box off,
hold off
So let's say that we want to have two bars only, like in the example above. And we need to use custom variable to tell bar() which bar we want to change. We created the variable in this line (newName=sprintf('cond_%d',i);) - it gave as a char of cond_1. When we call bar() like that bar(1, cond_1, 'FaceColor', 'Red','LineWidth',2) everything works fine, but when we want to use bar(2, newName, 'FaceColor', 'Blue','LineWidth',2) it gives an error Unrecognized option "cond_1".. I also added there title() function, which doesn't have this problem and understands char variables perfectly. title(newName); with our custom variable name newName is set correctly as a title. I used this method several times before, and it seems that this problem occurs only with bar() function. Does anyone have any idea how to fix it?
Thanks in advance for your help!
BM

Don’t use variable names like cond_1 and cond_2. Instead, your array z is all you need. z(i) is the element you want to color differently. Let’s take a slightly larger dat set as example:
z = 9*rand(1,10) + 9;
zz = 2*rand(1,10) + 1;
k = find(z>14) % the bars to color red
x = 1:10;
hold on
bar(x,z, 'FaceColor', 'Blue','LineWidth',2)
bar(x(k),z(k), 'FaceColor', 'Red','LineWidth',2)
errorbar(x,z,zz, 'color',[.44 .44 .44],'linestyle','none','linewidth',2)

Related

How can I build custom xticklabels using numbers and strings?

I am trying to customize the Xticklabels of my bar graph to have a format of 'number (units)'
So far I have a vector:
scanrate = [2;4;6;8;10];
I want my bar graph to have an x axis of:
2mv/s 4mv/s 6mv/s 8mv/s 10mv/s
If I use xticklabels(num2str(scanrate))
the xticklabels change to the numbers in the scanrate vector. I want to put mv/s after each Xtick.
You can also use strcat :
xticklabels(strcat(num2str(scanrate),' mv/s'))
Please note that it works only when scanrate is a column vector.
Fun fact :
num2str(scanrate) + " mv/s"
also works, but
num2str(scanrate) + ' mv/s'
does not
Build your strings using sprintf(), where the %d flag is for an unsigned integer:
my_labels = {};
for ii = 1:numel(scanrate)
my_labels{ii} = sprintf('%dmv/s', scanrate(ii));
end
figure;
% (...) make your plot
xticklabels(my_labels)
Alternative one-liner, thanks to Wolfie's comment:
my_labels = arrayfun(#(x)sprintf('%dmv/s',x),scanrate,'uni',0);
As a side note: that's normally not what you'd do when creating these type of plots. You'd just have numbers on the axes and a label stating something as "Velocity [mv/s]", rather than having the unit on every single tick label.

Hide lines of code in MATLAB

I want to know If it's possible and how, to hide some parts of a line or whole lines of code from a script in MATLAB. For example:
if a=b
x=y+1; x=x^2;
end
And have the x=x^2 hidden, but still run the process. I mean:
if a=b
x=y+1;
end
(wringing hands with evil grin on face)
If you really want to mess with people like this, you're going to want to go down the operator overloading route. Come with me on a journey where you will almost certainly shoot yourself in the foot while trying to play a joke on someone else!
(lightning crackles over the laughter of a madman)
I've discussed this in a few other questions before (here and here). Basically, you can change the default behavior of built-in operators for MATLAB data types. In this case, we'll change how the plus operator works for variables of class double (the default variable type). Make a folder called #double on your MATLAB path, then create a file called plus.m and put the following code inside it:
function C = plus(A, B)
C = builtin('plus', A, B);
if strcmp(inputname(1), 'y')
C = C.^2;
end
end
Now, try it for yourself...
>> y=1; % Initialize y
>> x=y+1
x =
4 % Wait a minute...
>> x=1+1
x =
2 % OK
>> x=1+y
x =
2 % OK
>> x=y+1
x =
4 % What?!
>> x=y+2;
x =
9 % No!!
>> y=3;
>> x=y+1
x =
16 % Oh noes! I've been hax0red!!11!1!
How it works:
The new plus function shadows the built-in one, so it gets called when performing addition on doubles. It first invokes the built-in plus to do the actual addition using the builtin function. This is necessary, because if you wrote C=A+B; here it would call the phony plus again and cause infinite recursion. Then, it uses the inputname function to check what the variable name of the first input to the function is. If it's 'y', we square the result before returning it.
Have fun!!!
...and remember to remove it when you're done. ;)
if a==b
x = y+1;
for ind = 1
x = x^2;
end
end
Bit of a wacky way, but you can collapse loop/end blocks like for and while loops. Simply click the - sign in the editor:
So for two or less lines this doesn't help you, but if you want to hide e.g. 40 lines, it shortens it appreciably.
Another option is to simply chuck in a hundred or so spaces and make it obfuscated:
if a==b
x = y+1; x = x^2;
end
Thanks to excaza the most obfuscated way of all to write x=x^2;:
eval(cast((sscanf('240,122,240,188,100,118', '%d,')./2)', 'like', ''))

Plotting brownian motion matlab

First of all, I just want to say that I'm not that used to using matlab, but I need for an assignment, I'm supposed to create a "brownian movement". My code is currently looking like this:
clf
hold on
prompt = 'Ge ett input';
size = input(prompt) ;
numParticles = input('Ange antal partiklar');
axis([-size size -size size]);
Part = [];
color = 'brkgmyco';
for i = drange(1:numParticles)
Part = [Part [0;0]];
end
for i = drange(1:200)
dxdy = randn(2,numParticles);
k = Part
Part = Part + dxdy;
My concern is how to print, I would even want like a small delay on every print, so you really can see what's happening for the assignment, is this possible to achieve from the code I've written for now or should anything be changed? Thanks in advance!
Here are some basic problems with your code, regardless of what you are trying to do:
You use size as a variable name. Doing so overrides MATLAB's function size.
The function zeros creates an array initialized by zeros, no need for a loop for that.
Instead of calculating randn for 200 times in a loop, you can do it once, with dxdy = randn(2,numParticles,200) and then simply refer to dxdy(:,:,i) within the loop.
The same holds for summation. Instead of summing within a loop to get the cumulative sum, use cumsum like Part = cumsum(randn(2,numParticles,200),3); and then refer to Part(:,:,i), within the loop.
Now to your task. You said you want to know how to print, but I believe you want to plot because you use some commands like axis, clf and hold, that refer to graphic objects. However, you never really do plot anything.
The basic and general function for plotting in 2D is plot, but there are many other more specific functions. One of them is scatter, and it has a sister function gscatter, that takes triples of x, y and groupand plot each (x(k),y(k)) colored by their group(k).
This code plots the particles on an axes, and animate their movement:
prompt = 'Ge ett input';
scope = input(prompt) ;
numParticles = input('Ange antal partiklar');
N = 500;
Part = cumsum(randn(2,numParticles,N)*scope/100,3);
h = gscatter(Part(1,:,1),Part(2,:,1),1:numParticles);
axis([-scope scope -scope scope]);
legend off
for k = 2:N
for p = 1:numParticles
h(p).XData = Part(1,p,k);
h(p).YData = Part(2,p,k);
end
drawnow
end
Is this what you look for?

How to access Matlab's handle object's sub-property: 'allowedStyles'

I would like to progmatically access the 'sub-property' of a lineseries object's 'MarkerFaceColor' property called 'allowedStyles'. This 'sub-property' can be seen in Matlab's inspector, (inspect(handle)) by expanding the 'MarkerFaceColor' property row.
I would like to do something like the following or get the equivalent of such a command.
allowedstyles = get(hh,'MarkerFaceColorAllowStyles');
Screen shot of Matlab's Inspect window indicating information I seek.
https://drive.google.com/file/d/0B0n19kODkRpSRmJKbkQxakhBRG8/edit?usp=sharing
update:
For completeness my final solution for accessing this information via a cellstr was to write the following function. Thanks to Hoki.
FYI, this information (allowed styles) is useful for a GUI when you want to offer user choices for a property such as MarkerFaceColor, where you don't know the type of graphics object they are modifying. I populate a listbox with these 'allowedStyles' along with an option to set a colour. Mesh plot 'MarkerFaceColor' allows styles {'none','auto','flat'}, while a lineseries plot has {'none','auto'}.
function out = getAllowedStyles(hh,tag)
% hh - handle returned from plot, surf, mesh, patch, etc
% tag - the property i.e. 'FaceColor', 'EdgeColor', etc
out = [];
try
aa = java(handle(hh(1)));
bb = eval(sprintf('aa.get%s.getAllowedStyles;',tag));
bb = char(bb.toString);
bb(1) = []; bb(end) = [];
out = strtrim(strsplit(bb,','));
end
end
I think it is indeed ReadOnly (or at least I couldn't find the correct way to set the property, but it is definitely readable.
You need first to access the handle of the underlying Java object, then call the method which query the property:
h = plot([0 1]) ; %// This return the MATLAB handle of the lineseries
hl = java(handle(h)) ; %// this return the JAVA handle of the lineseries
allowedstyles = hl.getMarkerFaceColor.getAllowedStyles ; %// this return your property :)
Note that this property is actually an integer index. Your inspect windows translate it to a string saying [none,auto] while in my configuration even the inspect windows only shows 1.
If you want the exact string translation of other values than one, you can call only the parent method:
hl.getMarkerFaceColor
This will display the allowed style in plain text in your console window.
ans =
com.mathworks.hg.types.HGMeshColor#28ba43dd[style=none,allowedStyles=[none, auto],red=0.0,green=0.0,blue=0.0,alpha=0.0]
If you insist on getting this property as a string progamatically, then you can translate the above using the toString method.
S = char( hl.getMarkerFaceColor.toString )
S =
com.mathworks.hg.types.HGMeshColor#1ef346e8[style=none,allowedStyles=[none, auto],red=0.0,green=0.0,blue=0.0,alpha=0.0]
then parse the result.

How to change the line properties of a plot in switch environment within a for-loop in Matlab

I have data from simulations in one single .dat file. Depending on certain criteria ('bu') that is contained in one column of the file (#13 here), I want to plot the data with different markers, while also defining the markersize and markerface properties.
What I have is a switch environment for the different cases - defining which markers and properties I want, and all this in a for-loop, to go through all simulation data.
I've tried the following:
for i=1:s1(1)
bu = data1(i,13);
switch bu
case 1
set(h,'kd','MarkerSize',14,'MarkerFaceColor','k');
case 2
set(h,'kd','MarkerSize',14);
case 3
set(h,'k>','MarkerSize',14,'MarkerFaceColor','k');
case 4
set(h,'ks','MarkerSize',14,'MarkerFaceColor','k');
case 5
set(h,'ks','MarkerSize',14);
case 6
set(h,'ko','markersize',14);
case 7
set(findobj(gca,'k^','MarkerSize',14,'MarkerFaceColor','k'));
end
figure(1);
h=plot(Re1(i),A1(i)); hold on
end
First I tried to use a handle 'h', but it said it was undefined, I guess since the h=plot comes later. Then I tried findobj in the last case (which is the case for the first simulation, so this gives the error in the first round), didn't work either ("Incomplete property-value pair" - not sure what it means here).
I also tried putting all these properties in a string like
str=['kd','MarkerSize',14,'MarkerFaceColor','k']
then plot with
h=plot(Re1(i),A1(i),str); hold on
but it doesn't work with/without brackets either.
Now I don't have any further ideas, thankful for any suggestions!
I think the easiest change for you is to put the plot options in a cell array in the switch block. For example:
options = {'kd', 'MarkerSize', 14, 'MarkerFaceColor', 'k'};
Later, when you plot:
plot(x, y, options{:})
Another way I've done it is to set variables and use them in the plot command:
style = 'kd';
markerSize = 14;
markerFaceColor = 'k';
plot(x, y, style, 'MarkerSize', markerSize, 'MarkerFaceColor', markerFaceColor);
There are few different ways to do that, one of them - create all plot objects before hand and then fill them with both data and formatting:
figureHandle = figure;
for i=1:s1(1)
plotHandle(i) = plot(0,0); %just creating valid handle for future here
end;
code above before your for loop with bu switch, and then in your switch
set(ph(i),'kd','MarkerSize',14,'MarkerFaceColor','k', 'Xdata', Re(1), 'Ydata', A1(i));
Approach with str would work too, except you would need two cell arrays - option nad value like that:
firstoption = 'kd';
option = {'MarkerSize','MarkerFaceColor'};
value = {14,'k'};
h=plot(Re1(i),A1(i),firstoption);
for i=1:length(option)
set(h,option{i},value{i});
end;