Showing command line output without all of the newlines - matlab

Let's just say I type 2+3 in MATLAB. It gives me this output :
>> 2+3
ans =
5
Why is the output coming after 2 newlines? How do I correct this ?
Ideally, I would get the following output
ans = 5

You can use the format command to change how the display of variables when printed. In your case, you'll likely want to use the 'compact' option
format compact
This will remove all of the unnecessary newlines.
2+3
% ans=
% 5
Unfortunately, there is no built-in way to display it all on the same line because MATLAB's display is built to deal with multi-dimensional data. You could overload the display command if you really wanted. You can create a folder named #double and then a function named display inside of that
#double/
display.m
Then inside of display.m you could do something like this
function display(x)
% If it's a scalar, then show it all on one line
if isscalar(x)
fprintf('%s = %g\n', inputname(1), x);
else
% Otherwise use the built-in display command
builtin('display', x)
end
end
Then it will automatically be used when you have a double variable
>> 2 + 3
% ans = 5
If you wanted to overload the display of other types of data (uint16, int8, uint8), you would need to do the same as above except put a copy within their # folders as well.

Related

Dynamically labelling in MATLAB

I have a MATLAB script which creates an matrix, 'newmatrix', and exports it as matrix.txt:
save -ascii matrix.txt newmatrix
In my script I also calculate the distance between certain elements of the matrix, as the size of the matrix depends on a variable 'width' which I specify in the script.
width = max(newmatrix(:,5)) - min(newmatrix(:,5))
x_vector = width + 2
And the variable x_vector is defined as width + 2
I want to know is it possible to export x_vector, labelling it as, eg my_vector $x_vector so that "my_vector 7.3" will be produced when the value of x_vector is equal to 7.3
I have tried:
save -ascii 'my_vector' + x_vector
But receive the following errors:
warning: save: no such variable +
warning: no such variable 'my_vector'
Three things:
1) I prefer to use functional form of the calls so that you can pass in variables rather than static strings.
save -ascii matrix.txt newmatrix
is equivalent to:
save('-ascii','matrix.txt','newmatrix')
In other words, in the first form all inputs get treated as string inputs to the function.
2) You can't add character arrays in Matlab. Rather you concatenate them or use sprintf.
name = sprintf('my_vector_%g',x_vector);
save('-ascii',name)
Note by using the functional form we can now pass in a variable. Note however this won't work because name should be either a valid option or a variable, and my_vector_7.3 isn't either.
3) I'm not entirely sure what you're asking, but I think you want the text file to say "my_vector 7.3". I don't think -ascii supports strings .... You could write something using fprintf.
fid = fopen('matrix.txt','w');
fprintf(fid,mat2str(new_matrix));
fprintf(fid,'\n');
fprintf(fid,'my_vector %g',x_vector);
fclose(fid);

How to share variables between different m files in Matlab

I have three m files using the same variables and carrying out calculations on these variables. I have made an index m file in which i have declared all the variables and I can share the variables to the remaining m files using the variable names. My problem is that the variable names change too often and then I have to change the variable names in all these files manually. How can I make a Matlab script which can automatically get the variable names and value from the index m file and put these to the remaining m files.
I feel like you just need a little example from where you could go on so here we go:
First calling each value with a different variable name. if you have a lot of values of the same type a array is easier like:
A0=0; A1=6; A2=12 %each one with its own name
B=zeros(16,1); %create an array of 16 numbers
B(1)= 0; %1 is the first element of an array so care for A0
B(2)= 6;
B(8)= 12;
disp(B); % a lot of numbers and you can each address individually
disp(B(8)); %-> 12
you can put all that in your script and try it. Now to the function part. Your function can have input, output, neither or both. If you just want to create data you wont need an input but an output.
save this as myfile1.m:
function output = myfile1()
number=[3;5;6]; %same as number(1)=3;number(2)=5;number(3)=6
%all the names just stay in this function and the variable name is chosen in the script
output = number; %output is what the file will be
end
and this as myfile2.m
function output = myfile2(input)
input=input*2;%double all the numbers
%This will make an error if "input" is not an array with at least 3
%elements
input(3)=input(3)+2; %only input(3) + 2;
output = input;
end
and now try
B=myfile1() %B will become the output of myfile1
C=myfile2(B) %B is the input of myfile2 and C will become the output
save('exp.mat','C')
I hope this will get you started.

MATLAB Overload plus operator

I want to create a function in MATLAB by using the plus operator (i.e. plus(a,b)) where when the user passes two strings, they are concatenated together and displayed as the result. However, every time I check on this, I get the error that I cannot implement built-in functions. Is it possible to do this in MATLAB and if it is possible, what is the procedure of doing it?
Any help on this problem is appreciated.
Create a directory called #char
Inside that directory place a function similar to the following:
function c = plus(a,b)
c = horzcat(a,b); %// if you want the result to be output
disp(c) %// if you want the result to be displayed
Ensure that the parent directory of the #char directory is on the MATLAB path (or is the Current Directory).
Use the function
>> 'abc' + 'def'
abcdef
ans =
abcdef

Matlab file name with zero-padded numbers

I have 11x11 matrices and I saved them as .mat files from F01_01 to F11_11.
I have to run a function Func on each file. Since it takes a long time, I want to write a script to run the function automatically:
for i=01:11
for j=01:11
filename=['F',num2str(i), '_', num2str(j),'.mat'];
load(filename);
Func(Fi_j); % run the function for each file Fi_j
end
end
But it doesn't work, Matlab cannot find the mat-files.
Could somebody please help ?
The problem
i=01;
j=01;
['F',num2str(i), '_', num2str(j),'.mat']
evaluates to
F1_1.mat
and not to
F01_01.mat
as expected.
The reason for this is that i=01 is a double type assignment and i equals to 1 - there are no leading zeros for these types of variables.
A solution
a possible solution for the problem would be
for ii = 1:11
for jj= 1:11
filename = sprintf('F_%02d_%02d.mat', ii, jj );
load(filename);
Func(Fi_j); % run the function for each file Fi_j
end
end
Several comments:
Note the use of sprintf to format the double ii and jj with leading zero using %02d.
You can use the second argument of num2str to format its output, e.g.: num2str(ii,'%02d').
It is a good practice to use string formatting tools when dealing with strings.
It is a better practice in matlab not to use i and j as loop counters, since their default value in matlab is sqrt(-1).
Here is an alternate solution, note that the solution by #Shai is more easily expanded to multiple digits but this one requires less understanding of string formatting.
for i=1:11
for j=1:11
filename=['F',num2str(floor(i/10)),num2str(mod(i,10)) '_', num2str(floor(j/10)),num2str(mod(j,10)),'.mat'];
load(filename);
Func(Fi_j); % run the function for each file Fi_j
end
end
The num2str can do zeropadding to fill the field. In the example below 4 is the desired field width+1.
num2str(1,'% 04.f')
Ans = 001

Matlab cat() function: index exceeds matrix dimensions

I am trying to concatenate an array of numbers from 1->(a-1) + (a+1)->n.
I was using the cat function
cat(2, 1:a-1, a+1:n)
but I am getting the error
Index exceeds matrix dimensions.
Unless I am completely mistaken, I am just trying to concatenate two matrices of numbers so I'm not quite sure why I'm getting this error.
I'm trying to accomplish this:
>> a = 3;
>> n = 10;
>> cat(2, 1:a-1, a+1:n)
ans =
[1,2,4,5,6,7,8,9,10]
Is this the wrong way to do it? Any idea why this error is coming up?
Do you have a variable called cat in your workspace?
>> cat(2, 2:3, 4:6) # this works fine
ans =
2 3 4 5 6
>> cat = 1:3; # introduce the variable 'cat'
>> cat(2, 2:3, 4:6) # now it breaks
??? Index exceeds matrix dimensions.
It looks like you have a variable named cat in the workspace. The clean way is, of course, to rename the variable: If you have a sufficiently recent version of Matlab (R2012x, I think), you can replace cat in the first line it gets assigned (select the variable to see the gray ticks to the right of the window, indicating where the variable occurs in the function), and use shift+enter to replace all occurrences. Or you can use the Find/Replace all function (make sure you only replace words, not substrings, though).
If you cannot replace the existing variable name, you can use square brackets for catenation along the first and/or second dimension:
cat(2,a,b)
is equivalent to
[a,b]
Just for completeness, the concatenation you're trying to accomplish can also be achieved like so:
R = 1:n;
R = R(R ~= a)
I personally think this looks cleaner than
R = [1:a-1 a+1:n]
but that's personal; I always feel a little confusion towards something like 1:a-1>5 (is it ((1:a)-1)>5 or (1:(a-1))>5 or (1:a)-(1>5) or ...). I just always have to think for a second, whereas I understand my solution instantly.