Matlab Title Formatting - matlab

For matlab script, when I create a title for a plot, I use the following command:
title(['Input ', x, '; Output', y]);
However, this returns a newline character whenever I use ',' on the above string. So it looks like the following:
Input
xValue
Output
yValue
Anyone knows how to make these strings appear on the same line? Thanks.

From the output shown, I'm inferring that x and y are cell values. If so, you could use something like:
title(strcat('Input=>', num2str(cell2mat(x)), '; Output=>', num2str(cell2mat(y))))
The result would be as follows for x={1} and y={2}:
The reason you got the output as you did initially was that, since x and y were cells, MATLAB automatically converted your statement to
title([{'Input '}, x, {'; Output'}, y]);
meaning that you passed a cell array to title; as such, it displayed each part of the title in a separate line.
Now, if on the other hand, x and y were simple numbers, use:
title(strcat('Input=>', num2str(x), '; Output=>', num2str(y)))

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.

Printing multiple disp functions with one for loop

So, I have a series of display functions, ranging from x1 to x7. These all contain both strings and variables like:
x1 = ['The result of the scalar multiplication of V and U: ',num2str(scalar_uv)];
x2 = similar to above but with for example a value on the cross multiplication of the two scalars.
Instead of printing out each one through:
disp(x1);
disp(x2);
disp(x3);
I thought it would be possible to print them all out through a for loop or perhaps a nested for loop but I just can't figure out how to do it. I preferably don't want straight up solutions (I won't say no to them) but rather some hints or tips of possible.
A simple example solution would be to make a cell array and loop through it, or use celldisp() to display it. But if you want to print nicely, i.e. formatted specifically, to the command window you can use the fprintf function and format in line breaks. For example:
for displayValue = {x1, x2, x3, x4}
fprintf('%s\n', displayValue{1});
end
If you want more formatting options, such as precision, or fieldwidth, the formatspec code (%s in the example) has many configurations. You can see them on the fprintf helpdoc. The \n just tells the fprintf function to create a newline when it prints.
Instead of creating seven different variables (x1...x7), just create a cell array to hold all your strings:
x{1} = ['The result of the scalar multiplication of V and U: ',num2str(scalar_uv)];
x{2} = ['Some other statement with a value at the end: ',num2str(somevar)];
Now you can write a loop:
for iX = 1:length(x)
disp(x{iX})
end
Or use cellfun to display them without a for loop:
cellfun(#disp,x)
If you really want to keep them named x1...x7, then you can use an eval statement to get your variable names:
for iX = 1:7
disp(eval(['x' num2str(iX)]));
end

how to write cell array to text file MATLAB, error with dlmwrite

I understand that this is a recurrent topic, I have tried understanding the answers that people provided but none of them seemed easy to transfer to my particular problem as the solutions are usually for an implementation that is too far from what I'm trying to do
Could anyone help with the following.
When I run the code below I get:
Error using dlmwrite (line 118)
The input cell array cannot be converted to a matrix.
Error in GAVNeuroScan (line 25)
dlmwrite(outputfile, CondRowDone);
I give an example of what I want to achieve in the comments at the end of the code.
If someone can help me getting the contents of CondRowDone to a text file as exemplified in the comments that would be great!
studyname='TestGav';
subjects={'504','505'};
conditions={'HighLabel','LowLabel','HighSound','LowSound'};
nCond=4;
GFPorBMR='GFP';
for curCond=1:length(conditions)
for curSubject=1:length(subjects)
gavRow{curSubject}=[subjects(curSubject) '-' conditions{curCond} '-' GFPorBMR '.avg'];
end
CondRowDone{curCond,:}=['GROUPAVG' '{' gavRow '}' 'G Y 1 N N' conditions{curCond} 'avg.'];
end
outputfile = [studyname '_GAV_' curSubject '.txt'];
dlmwrite(outputfile, CondRowDone);
% What I want is a text file that would look exactly like that. I think I'm
% not far but it fails to write...
%
% GROUPAVG {{HighLabel-504-GFP.avg} {HighLabel-505-GFP.avg}} G Y 1 N N {HighLabel.avg}
% GROUPAVG {{LowLabel-504-GFP.avg} {LowLabel-505-GFP.avg}} G Y 1 N N {LowLabel.avg}
% GROUPAVG {{HighSound-504-GFP.avg} {HighSound-505-GFP.avg}} G Y 1 N N {HighSound.avg}
% GROUPAVG {{LowSound-504-GFP.avg} {LowSound-505-GFP.avg}} G Y 1 N N {LowSound.avg}
From what I have seen using the debugger, you have a little bit of confusion between the curly braces as text and the curly braces to handle MATLAB cell arrays.
Here is a re-write of your for-loop to produce the cell array of strings you have given in your code example. Also, to produce the exact output you specified, subject and condition have to be given in a different order:
for curCond=1:length(conditions)
gavRow = [];
for curSubject=1:length(subjects)
if (curSubject ~= 1)
gavRow = [gavRow ' '];
end
gavRow = [gavRow '{' [conditions{curCond} '-' subjects{curSubject} '-' GFPorBMR '.avg'] '}'];
end
CondRowDone{curCond}=['GROUPAVG ' '{' gavRow '} ' 'G Y 1 N N {' conditions{curCond} '.avg}'];
end
As for the task of writing the strings to disk, MATLAB is telling you that it cannot handle your cell array as a matrix. When it comes to write cell arrays to disk, I think you have to write it yourself using low-level functions, like this:
outputfile = [studyname '_GAV_' curSubject '.txt'];
fid = fopen(outputfile, 'w');
for i=1:length(CondRowDone)
fprintf(fid, '%s\n', CondRowDone{i});
end
fclose(fid);
dlmwrite only handles numeric data. One way around this, if you have Excel, would be to use xlswrite - it can take in (some kinds of) cell arrays directly.
xlswrite(outputfile, CondRowDone);
Then, do some batch xls to csv conversion (for example, see this question and answers). To get a text file directly you'll need to use lower level commands (as in blackbird's answer).

Cannot get imagesc to work in Matlab

Would someone kindly please tell me why imagesc is not doing what I want it to:
I am trying to get a grid of chars out like:
http://wetans.net/word-search-worksheets-for-kids
Here is the code:
A = [5,16,18,4,9;
9,10,14,3,18;
2,7,9,11,21;
3,7,2,19,22;
4,9,10,13,8]
AAsChars = char(A + 96);
imagesc(AAsChars);
The short answer is - you are using the wrong function for your job. imagesc will take a map of values and convert it to intensities - one pixel per value. You want it to magically take a character value and turn it into the representation (many pixels) of the character that this represents (without regard to font, etc).
You probably want to create an empty background, then put text characters at the locations you want. Something like (not tested):
figure
imagesc(ones(5,5))
axis off
for t = 1:5
for k = 1:5
text(t, k, sprintf('%c', A(t,k) + 96))
end
end
This should put the string (character) at the location (i,j). Experiment a bit - not sure I have the syntax of text() and the formatting of the string (with "%c") right and can't check right now.
I think you are overcomplicating, this should simply do the trick:
char(A + 96)

Can't understand the warning

My code works but every time it runs through line 13 it writes on the command window :"Warning: Integer operands are required for colon operator
when used as index ".
The relevant part of my code looks like that:
filename = uigetfile;
obj = mmreader(filename);
nFrames=obj.NumberOfFrames;
for k = 1 : nFrames
this_frame = read(obj, k);
thisfig = figure();
thisax = axes('Parent', thisfig);
image(this_frame, 'Parent', thisax);
if k==1
handle=imrect;
pos=handle.getPosition;
end
partOf=this_frame(pos(2):pos(2)+pos(4),pos(1):pos(1)+pos(3));%this is line 13
vector(k)=mean2(partOf);
title(thisax, sprintf('Frame #%d', k));
end
Why this warning appears and can i ignore it?
It's probably because one or more of the following: pos(2), pos(2)+pos(4), pos(1) and pos(1)+pos(3) are not integers, which indices are supposed to be. You may want to use the round function to round them up to integer values.
Maayan,
The problem seems to occur from the values of your pos vector (and the value of the calculations you make to pos vector values).
This is the solution quoted from MathWorks(MATLAB) website:
http://www.mathworks.com/support/solutions/en/data/1-FA9A2S/?solution=1-FA9A2S
Modify the index computations using the FIX, FLOOR, CEIL, or ROUND functions to ensure that the indices are integers. You can test if a variable contains an integer by comparing the variable to the output of the ROUND function operating on that variable when MATLAB is in debug mode on the line containing the variable.