So I need to plot a function, let's say it's: y = sin( xk )
But I can only write the matlab code like:
x = -pi : .1 : pi;
y = sin(x);
plot(x,y);
If I try to do xk, then it cries about not knowing what k is. Any idea how I can plot functions with variables that contain subscripts (the subscripts are just descriptive, they don't hold any value)? Thanks
Variables cannot have subscripts. You don't have to reproduce the formula exactly in a MATLAB statement. This is fine to name variable just x, or xk, or x_k, etc.
On the other hand, if you have multiple vectors that you want to associate with the same name, you can put them into a cell array and get each vector as x{k}.
You can use subscripts in axes labels, title and text annotations using Tex (default) or Latex interpretor. Use underscore character followed by subscript in a text string.
title('y = sin(x_k)')
or
title('y = sin(x_{several chars})')
Related
I am trying to understand these by myself
,
I want to simulate some straight lines, in Matlab, as follows:
f(t,z)=a(z)t+b(z) where a(z) and b(z) are uniformly distributed random variable in the interval [-1,1] and t is time between [-2,2]. More simply: f(t)= at+b, and z is the random index of the constant (a,b) and let say [-1,+1] is the sample space for z and z is uniformly distributed.
Could anyone help me with the code? Is there any way to show the random generation of the straight line as an animation? Thank you very much for any help.
I am trying like this:
a= rand(-1,1);
b=rand(-1,1);
-2<t<2;
f=a*t+b;
plot(t, f);
But I am getting error Unrecognized function or variable 't'.
Your attempt is not valid MATLAB syntax,
-2<t<2 does not do anything, other than produce the error you're seeing because t does not exist
f = a*t+b you can't define functions like this, you probably want to use an anonymous function.
You can't plot t because you haven't defined it, and you can't plot f because you haven't properly defined that either in terms of a valid t.
You need to define some discrete values for t. In this case two values is enough, because you're only plotting straight lines anyway. You could use linspace or the colon operator to create a finer spaced array for whatever reason.
N = 10; % Number of lines to plot
t = [-2,2]; % We want lines between -2 and 2
a = rand(N,1)*2-1; % N random values between -1 and +1
b = rand(N,1)*2-1; % N random values between -1 and +1
f = #(t,z) a(z)*t + b(z); % Define f in terms of axis t and index z
% Plotting
figure; hold on;
for iz = 1:N
plot( t, f(t,iz) );
end
This gives an image something like this:
If you need an "animation", you could add a pause, e.g. pause(1) inside the loop
I plotted a bubble chart using scatter plot in Matlab with text lables on x axis and integer numbers on y axis. The bubble sizes are also considered as integer numbers. I included both code and figure of my chart. When I try to transform the figure to tikz using "matlab2tikz" library, I see the following error:
"Error using categorical/cat (line 69): Can not concatenate a double array and a categorical array".
I don't have any double numbers in my values. How can I transform this figure to tikz format?
x = ["C","A", "P", "K"]; %x lables
x1=categorical(x);
y = [33,68,200,14];% values
y1 = [48,177,200,16];
y2=[6,6,200,3];
sz = [35,7, 10, 56];%Bubble sizes
sz1=[25,7, 30, 53];
sz2=[44, 8,4,10];
scatter(x1,y,sz,'g','LineWidth',2);
hold on
scatter(x1,y1,sz1,'b','LineWidth',2);
hold on
scatter(x1,y2,sz2,'r','LineWidth',2);
hold off
legend({'y = Method1','y = Method2', 'y = Method3'},'Location','north');
title('NewModel');
ylabel('%Value');
saveas(gcf,'test.png');
You do have double numbers. y, y1 and y2 are double whereas x1 is categorical which is why you are getting that error.
For your case, the error can be fixed by changing the square brackets to curly brackets in line 4052. i.e. change:
data = [xData(:), yData(:)]; %line 4052 of matlab2tikz.m
to:
data = {xData(:), yData(:)};
The reason is what the error message says. You have categorical xData and double yData. These cannot be concatenated into a regular array. A cell array is for combining different types of data.
Similarly,
data=applyHgTransform(m2t,[xData(:), yData(:), zData(:)]); %line 4056 of matlab2tikz.m
should be modified to the following if you are plotting in 3D and have mixed data type:
data=applyHgTransform(m2t,{xData(:), yData(:), zData(:)});
I am a newcomer to Matlab and programming in general. My Cartesian to polar conversion function that I wrote doesn't work.
syms x y
function [r,theta]=something[x,y]
r=(x^2+y^2)^.5
theta=atan(x/y)
end
What you are trying to do is create a function script file, but you have a non-function declaration statement at the beginning of your file. You can't do this. As such, you need to remove the syms x y statement at the beginning of your code. Also, you aren't declaring your function properly. You need to use round braces, not square braces to define your input parameters.
I would also use atan2 instead of atan because it finds the proper four-quadrant arc-tangent of the Cartesian coordinates. Also, use sqrt not ^.5 to take the square root. It's more stable. Also, to properly handle vector inputs, you need to make sure that x and y use .^2 in the r calculation and not ^2. Therefore, do this instead:
function [r,theta]=something(x,y) %// Change
r=sqrt(x.^2 + y.^2); %// Change
theta=atan2(y, x); %// Change
end
Place that into a file called something.m, then you can go into the command prompt and do this:
[r,theta] = something(x,y);
x and y are the x and y values of your Cartesian coordinates. What's great is that x and y can be a single value, a vector or a matrix of any size.
You can use the cart2pol function:
[theta, rho] = cart2pol(x, y)
Or do this:
theta = atan2(y, x) % use atan2() instead of atan()
rho = sqrt(x.^2 + y.^2) % use sqrt() instead of .^5
This is very easy with complex numbers. Specifically, if the given Cartesian coordinates are interpreted as the real and imaginary parts of a complex number, then the polar coordinates are the magnitude (abs) and argument (angle) of that complex number:
>> z = x+1j*y;
>> r = abs(z);
>> theta = angle(z);
I am using the plot command in Octave to plot y versus x values. Is there a way such that the graph also shows the (x,y) value of every coordinate plotted on the graph itself?
I've tried using the help command but I couldn't find any such option.
Also, if it isn't possible, is there a way to do this using any other plotting function?
Have you tried displaying a text box at each coordinate?
Assuming x and y are co-ordinates already stored in MATLAB, you could do something like this:
plot(x, y, 'b.');
for i = 1 : numel(x) %// x and y are the same lengths
text(x(i), y(i), ['(' num2str(x(i)) ',' num2str(y(i)) ')']);
end
The above code will take each point in your graph and place a text box (with no borders) in the format of (x,y) where x and y are the coordinates for all of the points.
Note: You may have to play around with the position of the text boxes, because the above code will place each text box right on top of each pair of co-ordinates. You can play around by adding/subtracting appropriate constants in the first and second parameters of the text function. (i.e. text(x(i) + 1, y(i) - 1, .......); However, if you want something quick and for illustrative purposes, then the above code will be just fine.
Here's a method I've used to do something similar. Generating the strings for the labels is the most awkward part, really (I only had a single number per label, which is a lot simpler)
x = rand(1, 10);
y = rand(1, 10);
scatter(x, y);
% create a text object for each point
t = text(x, y, '');
% generate a cell array of labels - x and y must be row vectors in this case
c = strsplit(sprintf('%.2g,%.2g\n',[x;y]), '\n');
c(end) = []; % the final \n gives us an extra empty cell, remove it
c = c'; % transpose to match the dimensions of t
% assign each label to each text object
set(t, {'String'}, c);
You may want to play around with various properties like 'HorizontalAlignment', 'VerticalAlignment' and 'Margin' to tweak the label positions to your liking.
After a little more thought, here's an alternative, more robust way to generate a suitable cell array of coordinate labels:
c = num2cell([x(:) y(:)], 2);
c = cellfun(#(x) sprintf('%.2g,%.2g',x), c, 'UniformOutput', false);
There is a very useful package labelpoints
in MathWorks File Exchange that does exactly that.
It has a lot of convenient features.
I would like to define a matrix of symbolic functions (not variables) in Matlab. In the workspace I would like it to be an element of class symfun of size N-by-M (where N and M are positive integers).
You can't create a matrix of symfun class elements (possibly for the same reason that one can't create a matrix of function handles), but you can create a symbolic function that returns a matrix of symbolic expressions:
syms x y z;
Afun = symfun([x+y y-z;y/x z-1],[x y z])
B = Afun(sym(pi),cos(y),z^2)
Of course you won't be able to directly access the elements of Afun until you evaluate it, though you can use formula to extract them:
Amat = formula(Afun);
Amat(1)
It is possible to concatenate symfuns into a matrix, provided that they all have the same input arguments (the arguments don't need to be used). However, the concatenation still does not form a matrix of symfuns – it just concatenates the formulas themselves so you still end up with one symfun as above.
Another option is to create a matrix of symbolic expressions, e.g.:
syms x y z;
A = [2*x 3*y^2 x+z;
-y^3+1 sin(x) sym('pi');
3.5 exp(-z) 1/x];
which can be evaluated using subs:
B = subs(A,{x,y,z},{sym(pi),cos(y),z^2})
And normal matrix operations work, e.g.:
B = subs(A(2,:),{x,y,z},{sym(pi),cos(y),z^2})
I don't know how to create a matrix, but a cell is possible:
c={symfun(x+y, [x y]),symfun(x+2*y, [x y]);symfun(x+3*y, [x y]),symfun(x+4*y, [x y])}
Maybe this is sufficient in your case.
If you for example want to arrange some anonymous symbolic functions in a vector you can do as following:
z = sym([]); %declare z as an empty symbolic array
N = 6; %array size
for i = 1:N
syms(sprintf('z%d(t)', i)) %declare each element in the array as a single symbolic function
zz = symfun(sym(sprintf('z%d(t)', i)), t); %declare each element to a symbolic "handle"
z = [z;zz]; %paste the symbolic "handle" into an array
end
Be aware that matlab treats z as an 1x1 symbolic function even though it contains more elements.
z will still behave like a vector, so you can use it as a normal vector in matrix-vector operations.