I'm trying to add legends the plot when it adds a curve. I can't see whats wrong with my code, can someone please help? I'm using matlab r2015a on ubuntu.
x=1:5;
v=1:5;
plot(x,v)
[~,~,plots,str] = legend('1');
hold on
for i=4:10
pl=plot(x,v*i);
[~,~,plots,str]=legend([plots;pl],str,num2str(i))
end
when i run it i get:
plots =
1x2 Line array:
Line Line
str =
'1' '4'
Error using vertcat
Dimensions of matrices being
concatenated are not
consistent.
So its means it works the first lap but not the second.
As discussed in the comment, the way Matlab handles legends is different than in earlier releases; they are now legend objects.
In any case, to solve your problem, which is a dimension mismatch problem, you can simply concatenate vertically the outputs you get using the transpose operator, because Matlab returns a horizontal array of line and text objects whereas you want a vertical array. Therefore, using plots.' and pl.' works fine. Also, it's good practice not to use i as a loop counter since it represents the imaginary unit.
clear
clc
close all
x=1:5;
v=1:5;
plot(x,v)
[~,~,plots,str] = legend('1');
hold on
for k=4:10
pl=plot(x,v*k);
[LegendObject,~,plots,str]=legend([plots.';pl.'],str,num2str(k));
end
%// Use the legend object to modify its properties/location
set(LegendObject,'Location','NorthWest');
Output:
Related
I need your help again :). I'm trying to plot multiple lines for a very large dataset. To start easier, I divided the dataset to get a TABLE in Matlab that contains 6 columns, with the first column representing the date that I want on my x-axis. Now I want to plot the other columns (and in the original file are a lot more than 6 columns) on the y axis, using a for loop. I tried the following, with no success:
hold on
for i=2:1:6
plot(Doldenstock(:,1), Doldenstock(:,i));
end
hold off
As I understand this, this code would do exactly what I want for columns 2,3,4,5,6. However, I always get the same error code:
Error using tabular/plot
Too many input arguments.
Error in Plotting_bogeo (line 6)
plot(Doldenstock(:,1), Doldenstock(:,i));
Now, I don't know if maybe for loops like this don't work for tabes but only for arrays?
Thanks for your help in advance!
Cheers,
Tamara
The function plot(x) expect x to be a scalar, a vector, or a matrix. But in your case the input is a table, because accessing a table with parentheses return a table, which is not supported.
If you read the doc "how to access data in a table" you will figure out that you need to use curly brace {} to extract the raw data (in your case a 1D matrix).
So use:
plot(T{:,1},T{:,2})
I have a problem with the following code. I want to store all the values I am creating in the for loop below so that I can make a plot of it. I have tried several things, but nothing works. Does anyone know a simple method to create a vector of the results and then plot them?
dx=0.1;
t=1;
e=1;
for x=-1:dx:1
lower_bound=-100;
upper_bound=x/(sqrt(4*t*e));
e=1;
u=(1/sqrt(pi))*quad(#integ,lower_bound,upper_bound);
plot(x,u)
hold on
end
hold off
I would like to use as much of this matlab code as possible.
dx=0.1;
t=1;
e=1;
xval=[-1:dx:1].';
upper_bound = zeros(numel(xval),1);
u = zeros(numel(xval),1);
for ii=1:numel(xval)
x = xval(ii)
lower_bound=-100;
upper_bound(ii,1)=x/(sqrt(4*t*e));
u(ii,1)=(1/sqrt(pi))*quad(#integ,lower_bound,upper_bound(ii));
end
figure;
plot(xval,u)
by adding the (ii) behind your statements it saves your variables in an array. I did not use that on your lower_bound since it is a constant.
Note that I first created an array xval and called that with integers in ii, since subscriptindices must be positive integers in MATLAB. I also initialised both upper_bound and u by creating a zero matrix before the loop executes. This is handy since extending an existing vector is very memory and time consuming in MATLAB and since you know how big they will get (same number of elements as xval) you might as well use that.
I also got the plot call outside the loop, to prevent you from plotting 21 blue lines in 1 plot.
I get some strange problem in my matlab code, this is a part of my code:
for k=1:length(box11)
num_pts1(k)=sum(length(find(box11(:,k)>0)));
size1=sum(length(find(box11(:,:)>0)));
perc1(k)=(num_pts1(k)/size1)*100;
end
plot(delta,perc1(k),'*')
However, the problem is that I get perc1 fixed in my plot. so I see a straight line in the graph. but I would like to have different numbers which give a curve line to me..
plzzzzzzzzzzzzzzzz, any help :( !!!
You should recall that length returns the length of an array. So, in the instruction
num_pts1(k)=sum(length(find(box11(:,k)>0)));
the operator sum acts on a scalar (which equals the length of the array find(box11(:,k)>0)), and not on an array. The same holds true for the instruction
size1=sum(length(find(box11(:,:)>0)));
So, if the length of find(box11(:,k)>0) does not change with k, then your perc1 will keep constant.
I have this cell (16x1) in MATLAB:
eventIDs =
'explosion'
'light'
'darkness'
'atomic'
...
..
now I want to use this :
%First bar plotting!
bar(duration_vector);
d = size(duration_vector);
labels = cell2mat(eventIDs);
xticklabel_rotate([1:d],45,eventIDs,'interpreter','none');
set(gca, 'XTick', 1:d, 'XTickLabel', labels);
I want to plot a bar graph but my events I too long, and I want them rotated to look good!
but when I run the code
I get this:
??? Error using ==> cat
CAT arguments dimensions are not consistent.
Error in ==> cell2mat at 85
m{n} = cat(1,c{:,n});
Error in ==> extract_data at 52
labels = cell2mat(eventIDs);
You don't need to do cell2mat. That tries to create a 2D matrix of characters (which fails because your strings are different lengths).
You also don't need the set(... line because xticklabel_rotate already sets the labels.
cell2mat in Matlab only works if your cell has a consistent number of columns in all rows. That is so because Matlab can't handle normal arrays with a variable number of columns per row, and that's generally the case of string matrices.
That said, cell manipulations is almost equal to matrix manipulation, the only difference being the indexation method: matrices use square brackets ([) and cells use curly brackets.
I googled the code of this function you're using, the xticklabel_rotate, and found the fileexchange link to the function here. There, the example given by the author uses a cell, instead of a matrix.
So I'm guessing that you can drop this cell2mat off because I thik you don't need to set the Xticks with the set function you're using. The xticklabel_rotate should do that.
I think you should try this:
%First bar plotting!
bar(duration_vector);
d = size(duration_vector);
xticklabel_rotate([1:d],45,eventIDs,'interpreter','none');
I am a complete novice at using matlab and am trying to work out if there is a way of optimising my code. Essentially I have data from model outputs and I need to plot them using matlab. In addition I have reference data (with 95% confidence intervals) which I plot on the same graph to get a visual idea on how close the model outputs and reference data is.
In terms of the model outputs I have several thousand files (number sequentially) which I open in a loop and plot. The problem/question I have is whether I can preprocess the data and then plot later - to save time. The issue I seem to be having when I try this is that I have a legend which either does not appear or is inaccurate.
My code (apolgies if it not elegant):
fn= xlsread(['tbobserved' '.xls']);
time= fn(:,1);
totalreference=fn(:,4);
totalreferencelowerci=fn(:,6);
totalreferenceupperci=fn(:,7);
figure
plot(time,totalrefrence,'-', time, totalreferencelowerci,'--', time, totalreferenceupperci,'--');
xlabel('Year');
ylabel('Reference incidence per 100,000 population');
title ('Total');
clickableLegend('Observed reference data', 'Totalreferencelowerci', 'Totalreferenceupperci','Location','BestOutside');
xlim([1910 1970]);
hold on
start_sim=10000;
end_sim=10005;
h = zeros (1,1000);
for i=start_sim:end_sim %is there any way of doing this earlier to save time?
a=int2str(i);
incidenceFile =strcat('result_', 'Sim', '_', a, 'I_byCal_total.xls');
est_tot=importdata(incidenceFile, '\t', 1);
cal_tot=est_tot.data;
magnitude=1;
t1=cal_tot(:,1)+1750;
totalmodel=cal_tot(:,3)+cal_tot(:,5);
h(a)=plot(t1,totalmodel);
xlim([1910 1970]);
ylim([0 500]);
hold all
clickableLegend(h(a),a,'Location','BestOutside')
end
Essentially I was hoping to have a way of reading in the data and then plot later - ie. optimise the code.
I hope you might be able to help.
Thanks.
mp
Regarding your issue concerning
I have a legend which either does not
appear or is inaccurate.
have a look at the following extracts from your code.
...
h = zeros (1,1000);
...
a=int2str(i);
...
h(a)=plot(t1,totalmodel);
...
You are using a character array as index. Instead of h(a) you should use h(i). MATLAB seems to cast the character array a to double as shown in the following example with a = 10;.
>> double(int2str(10))
ans = 49 48
Instead of h(10) the plot handle will be assigned to h([49 48]) which is not your intention.