How to remove coordinate specific entries from a matrix? - matlab

I'm having trouble to implement this (seemingly) simple task in Octave/Matlab.
I want to remove specific entries of a set of 2dimensional data. I have sample data (points of x and y coordinates) which contain specific areas that should not be further processed. I want to delete these areas from my sample data.
Here is an example for further understanding what I want to achieve. I would like to have:
B = A except the data in the red rectangle
Code Sample:
x = 0:pi/64:4*pi;
y = sin(x);
A = [x; y];
% Boundaries of the data that should be deleted
x1 = 4;
x2 = 6;
y1 = -1;
y2 = -0.5;
figure;
hold on;
plot(A(1,:),A(2,:),'bo');
plot([x1 x2 x2 x1 x1],[y1 y1 y2 y2 y1],'r-');
I know how to select the data within the red rectangle, which can be done with this command:
indices = find(A(1,:)>x1 & A(1,:)<x2 & A(2,:)>y1 & A(2,:)<y2);
B(1,:) = A(1,indices);
B(2,:) = A(2,indices);
plot(B(1,:),B(2,:),'g-x');
But I need the opposite: Select the data outside the red rectangle.
Any help is appreciated.

Invert all of the operators in your statement defining indices (i.e. > becomes < and vice-versa, AND[ & ] becomes OR[ | ]).
indices2 = find(A(1,:)<x1 | A(1,:)>x2 | A(2,:)<y1 | A(2,:)>y2);
B=A(:,indices2);
plot(B(1,:),B(2,:),'g-x');

Use logical arrays to select data
A very handy way of managing selections is the use of logical arrays. This is faster than using indices and allows the easy inversion of a selection as well as the combination of multiple selections. Here comes the modified selection function:
sel = A(1,:)>x1 & A(1,:)<x2 & A(2,:)>y1 & A(2,:)<y2
The result is a logical array that is a very memory efficient and fast representation of your information.
See figure for graphical representation of output.
Code Example
x = 0:pi/64:4*pi;
y = sin(x);
% Combine data: This is actually not necessary
% and makes the method more complicated. If you can stay with x and y
% arrays formulation becomes shorter
A = [x; y];
% Boundaries of the data that should be deleted
x1 = 4;
x2 = 6;
y1 = -1;
y2 = -0.5;
% Select interesting data
sel = A(1,:)>x1 & A(1,:)<x2 & A(2,:)>y1 & A(2,:)<y2;
% easily invert selection with the rest of data
invsel = ~sel;
% Get selected data to a new array
B1 = A(:,sel);
B2 = A(:,invsel);
% Display your data
figure;
hold on;
plot(B1(1,:),B1(2,:),'bo');
plot(B2(1,:),B2(2,:),'rx');
% Plot selection box in green
plot([x1 x2 x2 x1 x1],[y1 y1 y2 y2 y1],'g-');
Graphical Result
octave
matlab

Related

Adding two color maps using imagesc between two sets of curves with specified boundaries (MATLAB)

I'm trying to add two color gradients between two curves (in this example these are lines).
This is the code for what I've done so far
% the mesh
ns=1000;
t_vec = linspace(0,100,ns);
x_vec = linspace(-120,120,ns);
[N, X] = meshgrid(t_vec, x_vec);
% the curves
x1 = linspace(0,100,ns); x2 = linspace(10,110,ns);
y1 = linspace(-50,50,ns); y2 = linspace(-20,80,ns);
X1 = repmat(x1, [size(N, 1) 1]); X2 = repmat(x2, [size(N, 1) 1]);
Y1 = repmat(y1, [size(N, 1) 1]); Y2 = repmat(y2, [size(N, 1) 1]);
% the gradient function
cc = #(x,x2,x1) ...
1./(1+(exp(-x)./(exp(-x1)-exp(-x2))));
for i=1:ns
CData1(:,i)=cc(x_vec,x2(i),x1(i));
CData2(:,i)=cc(x_vec,y2(i),y1(i));
end
CData=CData1+CData2; % here I've added the two gradients
% mask
mask = true(size(N));
mask((X > Y2 | X < Y1) & (X > X2 | X < X1)) = false;
% finalized data
Z = NaN(size(N));
Z(mask) = CData(mask);
Z = normalize(Z, 1, 'range');
% draw a figure!
figure(1); clf;
ax = axes; % create some axes
sc = imagesc(ax, t_vec, x_vec, Z); % plot the data
colormap('summer')
ax.YDir = 'normal' % set the YDir to normal again, imagesc reverses it by default;
hold on
plot(t_vec,x1,'r',t_vec,x2,'r',t_vec,y1,'k',t_vec,y2,'k')
ylim([-120 120]); xlim([0 100])
the result I get is
As you can see, the gradient stretches between the most lower line to the most upper line.
How can I separate between the two color data and present them in the same image (using imagesc) using a different colormap?
Here is a function called comat (see at the bottom of the answer) that I once made for something similar, I think you might find it useful in your case. Here's an example how to use it:
imagesc(t_vec, x_vec, comat(CData2.*mask,CData1.*mask));
colormap([summer(256).^2;flipud(bone(256).^0.5)]); % and the two colormaps
set(gca,'Ydir','normal')
The result is:
I'm not sure this is what you meant, but you can see how the data of the thin stripe is only visualized using the bone b&w colormap, while the rest is with summer. I also "abused" the colormaps with a ^ factor for emphasizing the range of the gradient.
function z = comat(z1,z2,DR)
% the function combines matrices z1 and z2 for the purpose of
% visualization with 2 different colormaps
% z1,z2 - matrices of the same size
% DR - the dynamic range for visualization (default 256)
%example
%imagesc(comat(z1,z2)); colormap([jet(256);bone(256)]);
%defaults
if (nargin < 3); DR=256; end
%normalize to dynamic range, integer values in the range 0 to DR
z1=double(uint32(DR*(z1-min(z1(:)))./(max(z1(:)-min(z1(:))))));
z2=double(uint32(DR*(z2-min(z2(:)))./(max(z2(:)-min(z2(:))))+DR+1));
thr=DR+2+10; %threshold where data is not important for z2, must be at least DR+2
z=z1.*(z2<thr)+z2.*(z2>thr);
end

Constrained linear least squares not fitting data

I am trying to fit a 3D surface polynomial of n-degrees to some data points in 3D space. My system requires the surface to be monotonically increasing in the area of interest, that is the partial derivatives must be non-negative. This can be achieved using Matlab's built in lsqlin function.
So here's what I've done to try and achieve this:
I have a function that takes in four parameters;
x1 and x2 are my explanatory variables and y is my dependent variable. Finally, I can specify order of polynomial fit. First I build the design matrix A using data from x1 and x2 and the degree of fit I want. Next I build the matrix D that is my container for the partial derivatives of my datapoints. NOTE: the matrix D is double the length of matrix A since all datapoints must be differentiated with respect to both x1 and x2. I specify that Dx >= 0 by setting b to be zeroes.
Finally, I call lsqlin. I use "-D" since Matlab defines the function as Dx <= b.
function w_mono = monotone_surface_fit(x1, x2, y, order_fit)
% Initialize design matrix
A = zeros(length(x1), 2*order_fit+2);
% Adjusting for bias term
A(:,1) = ones(length(x1),1);
% Building design matrix
for i = 2:order_fit+1
A(:,(i-1)*2:(i-1)*2+1) = [x1.^(i-1), x2.^(i-1)];
end
% Initialize matrix containing derivative constraint.
% NOTE: Partial derivatives must be non-negative
D = zeros(2*length(y), 2*order_fit+1);
% Filling matrix that holds constraints for partial derivatives
% NOTE: Matrix D will be double length of A since all data points will have a partial derivative constraint in both x1 and x2 directions.
for i = 2:order_fit+1
D(:,(i-1)*2:(i-1)*2+1) = [(i-1)*x1.^(i-2), zeros(length(x2),1); ...
zeros(length(x1),1), (i-1)*x2.^(i-2)];
end
% Limit of derivatives
b = zeros(2*length(y), 1);
% Constrained LSQ fit
options = optimoptions('lsqlin','Algorithm','interior-point');
% Final weights of polynomial
w_mono = lsqlin(A,y,-D,b,[],[],[],[],[], options);
end
So now I get some weights out, but unfortunately they do not at all capture the structure of the data. I've attached an image so you can just how bad it looks. .
I'll give you my plotting script with some dummy data, so you can try it.
%% Plot different order polynomials to data with constraints
x1 = [-5;12;4;9;18;-1;-8;13;0;7;-5;-8;-6;14;-1;1;9;14;12;1;-5;9;-10;-2;9;7;-1;19;-7;12;-6;3;14;0;-8;6;-2;-7;10;4;-5;-7;-4;-6;-1;18;5;-3;3;10];
x2 = [81.25;61;73;61.75;54.5;72.25;80;56.75;78;64.25;85.25;86;80.5;61.5;79.25;76.75;60.75;54.5;62;75.75;80.25;67.75;86.5;81.5;62.75;66.25;78.25;49.25;82.75;56;84.5;71.25;58.5;77;82;70.5;81.5;80.75;64.5;68;78.25;79.75;81;82.5;79.25;49.5;64.75;77.75;70.25;64.5];
y = [-6.52857142857143;-1.04736842105263;-5.18750000000000;-3.33157894736842;-0.117894736842105;-3.58571428571429;-5.61428571428572;0;-4.47142857142857;-1.75438596491228;-7.30555555555556;-8.82222222222222;-5.50000000000000;-2.95438596491228;-5.78571428571429;-5.15714285714286;-1.22631578947368;-0.340350877192983;-0.142105263157895;-2.98571428571429;-4.35714285714286;-0.963157894736842;-9.06666666666667;-4.27142857142857;-3.43684210526316;-3.97894736842105;-6.61428571428572;0;-4.98571428571429;-0.573684210526316;-8.22500000000000;-3.01428571428571;-0.691228070175439;-6.30000000000000;-6.95714285714286;-2.57232142857143;-5.27142857142857;-7.64285714285714;-2.54035087719298;-3.45438596491228;-5.01428571428571;-7.47142857142857;-5.38571428571429;-4.84285714285714;-6.78571428571429;0;-0.973684210526316;-4.72857142857143;-2.84285714285714;-2.54035087719298];
% Used to plot the surface in all points in the grid
X1 = meshgrid(-10:1:20);
X2 = flipud(meshgrid(30:2:90).');
figure;
for i = 1:4
w_mono = monotone_surface_fit(x1, x2, y, i);
y_nr = w_mono(1)*ones(size(X1)) + w_mono(2)*ones(size(X2));
for j = 1:i
y_nr = w_mono(j*2)*X1.^j + w_mono(j*2+1)*X2.^j;
end
subplot(2,2,i);
scatter3(x1, x2, y); hold on;
axis tight;
mesh(X1, X2, y_nr);
set(gca, 'ZDir','reverse');
xlabel('x1'); ylabel('x2');
zlabel('y');
% zlim([-10 0])
end
I think it may have something to do with the fact that I haven't specified anything about the region of interest, but really I don't know. Thanks in advance for any help.
Alright I figured it out.
The main problem was simply an error in the plotting script. The value of y_nr should be updated and not overwritten in the loop.
Also I figured out that the second derivative should be monotonically decreasing. Here's the updated code if anybody is interested.
%% Plot different order polynomials to data with constraints
x1 = [-5;12;4;9;18;-1;-8;13;0;7;-5;-8;-6;14;-1;1;9;14;12;1;-5;9;-10;-2;9;7;-1;19;-7;12;-6;3;14;0;-8;6;-2;-7;10;4;-5;-7;-4;-6;-1;18;5;-3;3;10];
x2 = [81.25;61;73;61.75;54.5;72.25;80;56.75;78;64.25;85.25;86;80.5;61.5;79.25;76.75;60.75;54.5;62;75.75;80.25;67.75;86.5;81.5;62.75;66.25;78.25;49.25;82.75;56;84.5;71.25;58.5;77;82;70.5;81.5;80.75;64.5;68;78.25;79.75;81;82.5;79.25;49.5;64.75;77.75;70.25;64.5];
y = [-6.52857142857143;-1.04736842105263;-5.18750000000000;-3.33157894736842;-0.117894736842105;-3.58571428571429;-5.61428571428572;0;-4.47142857142857;-1.75438596491228;-7.30555555555556;-8.82222222222222;-5.50000000000000;-2.95438596491228;-5.78571428571429;-5.15714285714286;-1.22631578947368;-0.340350877192983;-0.142105263157895;-2.98571428571429;-4.35714285714286;-0.963157894736842;-9.06666666666667;-4.27142857142857;-3.43684210526316;-3.97894736842105;-6.61428571428572;0;-4.98571428571429;-0.573684210526316;-8.22500000000000;-3.01428571428571;-0.691228070175439;-6.30000000000000;-6.95714285714286;-2.57232142857143;-5.27142857142857;-7.64285714285714;-2.54035087719298;-3.45438596491228;-5.01428571428571;-7.47142857142857;-5.38571428571429;-4.84285714285714;-6.78571428571429;0;-0.973684210526316;-4.72857142857143;-2.84285714285714;-2.54035087719298];
% Used to plot the surface in all points in the grid
X1 = meshgrid(-10:1:20);
X2 = flipud(meshgrid(30:2:90).');
figure;
for i = 1:4
w_mono = monotone_surface_fit(x1, x2, y, i);
% NOTE: Should only have 1 bias term
y_nr = w_mono(1)*ones(size(X1));
for j = 1:i
y_nr = y_nr + w_mono(j*2)*X1.^j + w_mono(j*2+1)*X2.^j;
end
subplot(2,2,i);
scatter3(x1, x2, y); hold on;
axis tight;
mesh(X1, X2, y_nr);
set(gca, 'ZDir','reverse');
xlabel('x1'); ylabel('x2');
zlabel('y');
% zlim([-10 0])
end
And here's the updated function
function [w_mono, w] = monotone_surface_fit(x1, x2, y, order_fit)
% Initialize design matrix
A = zeros(length(x1), 2*order_fit+1);
% Adjusting for bias term
A(:,1) = ones(length(x1),1);
% Building design matrix
for i = 2:order_fit+1
A(:,(i-1)*2:(i-1)*2+1) = [x1.^(i-1), x2.^(i-1)];
end
% Initialize matrix containing derivative constraint.
% NOTE: Partial derivatives must be non-negative
D = zeros(2*length(y), 2*order_fit+1);
for i = 2:order_fit+1
D(:,(i-1)*2:(i-1)*2+1) = [(i-1)*x1.^(i-2), zeros(length(x2),1); ...
zeros(length(x1),1), -(i-1)*x2.^(i-2)];
end
% Limit of derivatives
b = zeros(2*length(y), 1);
% Constrained LSQ fit
options = optimoptions('lsqlin','Algorithm','active-set');
w_mono = lsqlin(A,y,-D,b,[],[],[],[],[], options);
w = lsqlin(A,y);
end
Finally a plot of the fitting (Have used a new simulation, but fit also works on given dummy data).

How to plot a matlab function for different parameters using hold on command

I have a matlab function that contain some constant parameter, I want to draw that function, on say same figure, using hold on (probably) while changing the value of that constant.
This my code:
close all
clear all
clc
m = 5;
x = 1:1:10;
y = m*x + 10;
h1 = figure;
plot(x,y)
m = 10;
figure(h1);
hold on
plot(x,y,': r')
When I tried using this code, I got two lines coincident on each others; and it looks matlab just used last value for the parameter m how can I make it use different values.
I found some stuff here, but doesn't fulfill my needs.
Any suggestions?
You need to recalculate y as well:
m = 5;
x = 1:1:10;
y = m*x + 10;
h1 = figure;
plot(x,y); hold on;
m = 10;
y = m*x + 10;
figure(h1);
plot(x,y,': r')
Or create an anonymous function:
x = 1:1:10;
f = #(m) m*x + 10;
%// and then:
h1 = figure;
plot(x,f(5) ); hold on;
plot(x,f(10),': r');
Currently, you're only updating m but you also have to calculate y again. This is why it plots exactly the same y (i.e. m is still 5) function when you issue the second plot.
You might want to use a simple for loop for that, like:
m = 5;
x = 1:1:10;
figure;
hold on;
for m=1:1:10
y = m*x + 10;
plot(x,y,': r')
end
In addition to the short answer - improving the plot..
%% Data Preparations
x = 1:10;
ms = 3; % number of different slopes
%% Graph Preparations
hold on;
% Prepare the string cell array
s = cell(1, ms);
% Handle storage
h = zeros(1, ms);
% Plot graphs
for m=1:ms
y = m*x + 10;
h(m)= plot(x,y,'Color',[1/m rand() rand()]);
s{m} = sprintf('Plot of y(m=%d)', m);
end
% Plot all or select the plots to include in the legend
ind = [ms:-1:1] .* ones(1,ms); % plot all
%ind = [ 1 3 4 ]; % plot selected
% Create legend for the selected plots
legend(h(ind), s{ind});
Additional advice: When working with MATLAB and you try to improve the performance of your code, you shoud try to avoid using for-loops since MATLAB is MATrix manipulation and that's what it can do best. Ones you've taken this philosophy in, you'll create the most beautiful code one-liners! ;)
This script is an adoption of Steve Lord's post.

plotting scatter3 and surf plots from loop in matlab

I want to plot scatter3 and surf plots from a loop. Below is my code but it isn't working...not sure where I'm going wrong but clearly something is wrong with the z matrix?
for e = 1:10;
x = rand(1,3);
y = rand(1,3);
A = x+y;
subplot(2,2,1)
p = find(A(:,1) > 1.1 & A(:,1) < 1.6);
Result = A(p,:);
scatter3(Result(:,1), Result(:,2), Result(:,3))
hold on
z(e,:) = [Result(1) Result(2) Result(3)];
end
subplot(2,2,2)
surf(z)
I will reiterate what I said in my comment to you. I got this error message when trying to run your code: Attempted to access Result(1); index out of bounds because numel(Result)=0. This is because your p condition isn't satisfied - MATLAB could not find any elements in the first column that are between 1.1 and 1.6.
As such, what I would suggest you do is check to see if Result is empty before trying to access the value itself. However, I would suggest you don't write a loop and generate all of the random values at once, then do the filtering with the Boolean conditions. Therefore, the equivalent code without using a loop would be this:
x = rand(10,3);
y = rand(10,3);
A = x+y;
p = A(:,1) > 1.1 & A(:,1) < 1.6;
z = A(p,:);
figure;
subplot(2,1,1);
scatter3(z(:,1), z(:,2), z(:,3));
subplot(2,1,2);
surf(z);
We generate 10 3D points for x and y at the beginning, then add these and store this into A. Next, we find the rows in A that are between 1.1 and 1.6 in the first column and store this as a logical array. We then use this array to index into A and store the results into z. This is the recommended approach if you want to extract certain elements into an array rather than using find.
Once we obtain z, we plot these points with scatter, then also find a surface plot with surf for the same matrix. BTW, I've fixed your subplot as you are only creating two plots, yet you are allocating space for 4 plots.
If you're absolutely bent on using your code, you would simply do this:
z = []; %// Change
for e = 1:10
x = rand(1,3);
y = rand(1,3);
A = x+y;
subplot(2,1,1)
p = find(A(:,1) > 1.1 & A(:,1) < 1.6);
Result = A(p,:);
scatter3(Result(:,1), Result(:,2), Result(:,3))
hold on
if ~isempty(Result) %// Change here
z = [z; Result(1) Result(2) Result(3)]; %// Change
end
end
subplot(2,1,2)
surf(z)
What's important is the initialization of z. I made this empty, and we only add to z if Result is not empty - this will happen if you generate a number that is not between 1.1 and 1.6.

Plotting histogram side by side in Matlab

I have two vectors, c and d, whose histogram I need to plot side by side in the same figure in matlab. when i do
hist(c);
hold on;
hist(d)
the scale changes and I cant see the histogram of c vector. Where am i going wrong? Any help will be appreciated.
If you want the two to be in the same figure, you could try adjusting the X and Y limits to suit your needs (try help xlim and help ylim). However plotting them in the same figure might not always suit your needs, as a particular plot has to of course maintain a certain limit for X and Y.
If displaying them side by side in different figures would suffice however, you could consider using subplot():
>> A=[1 1 1 2 2];
>> B=[1 2 2 2 2];
>> figure(1);
>> hold on;
>> subplot(1,2,1);
>> hist(A);
>> subplot(1,2,2);
>> hist(B);
Resultant figure:
Notice how the different axis limits are maintained.
You can use axis([xmin xmax ymin ymax]) to control the x and y axis and select a range that will display both histograms. Depending on what you want your plot to look like, you may also want to try using nelements = hist(___) to get the number of elements in each bin and then plot them using bar(x,nelements) to control the location of each bar.
hist assumes you want to divide the range into 10 equal sized bins by default. If you want to use the same bins for both histograms, first find the range of your values and make a set of bin centers (e.g. binCenters = linspace(min(x), max(x), 15)'), then callhist(x, binCenters)`.
I use MATLAB histograms quite frequently and have wrote this small matlab script to plot two histograms (first one red and second blue) in one figure. The script is quite simple but the important thing is that the histograms should be comparable (i.e. equally spaced frequency bins).
function myhist(varargin)
% myhist function to plot the histograms of x1 and x2 in a single figure.
% This function uses the same xvalue range and same bins to plot the
% histograms, which makes comparison possible.
if nargin<2
x1 = cell2mat(varargin(1));
x2 = x1;
res = 100;
elseif nargin==2
x1 = cell2mat(varargin(1));
if length(cell2mat(varargin(2)))==1
res = cell2mat(varargin(2));
x2 = x1;
else
x2 = cell2mat(varargin(2));
res = 100;
end
elseif nargin>2
x1 = cell2mat(varargin(1));
x2 = cell2mat(varargin(2));
res = cell2mat(varargin(3));
end
if numel(x1)~=length(x1) || numel(x2)~=length(x2)
error('Inputs must be vectors.')
return
end
xrangel = max(min(x1),min(x2));
xrangeh = min(max(x1),max(x2));
x1_tmp = x1(x1>=xrangel & x1<=xrangeh);
x2_tmp = x2(x2>=xrangel & x2<=xrangeh);
xbins = xrangel:(xrangeh - xrangel)/res:xrangeh;
hist(x1_tmp,xbins)
hold on
h = findobj(gca,'Type','patch');
set(h,'FaceColor','r','EdgeColor','w');
hist(x2_tmp,xbins)