plotting from a loop in matlab - matlab

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.

Related

“Index exceeds the number of array elements” for piecewise function

I am trying to create piecewise functions V(t), D(t).
I try to find the piecewise, then I use the piecewise of t to construct functions and plot them.
But it shows "Index exceeds the number of array elements. Index must not exceed 51".
How can I fix it?
I put my code below and I really hope someone can answer it. Thaks!
z=zeros(1,50);
p_i=zeros(1);
p=0.023;
for i=1:50
z(i)=rand;
if z(i)>p
p_i(end+1)=i+z(i);
end
end
n=numel(p_i);
V=zeros(1,n);
w=zeros(1,n);
D=zeros(1,n);
V_op=zeros(1,n);
%get the number of pi
sigma_w0=0.2;
Q=5;
P=2;
Q_op=4;
for i=1:n
if i>1
w(i)=w(i-1)+normrnd(0,sigma_w0);
V(i)=Q*w(i);
D(i)=P*w(i);
V_op(i)=Q_op*w(i);
else
w(1)=2;
V(i)=Q*w(i);
D(i)=P*w(i);
V_op(i)=Q_op*w(i);
end
end
t=0:0.0002:50;
V_p=zeros(size(t));
D_p=zeros(size(t));
V_opp=zeros(size(t));
for m=1:length(t)
t(m)>=p_i(i)& t(m)<p_i(i+1)
V_p(m)=V(i);
D_p(m)=D(i);
V_opp(m)=V_op(i);
end
Yes, if you run your code you'll see it is functional before the last for loop since it is evaluating that in the 1 to 50 range (m=1:length(t)) but your line is printing 51 values so you need to check only the next part and reorganize the idea:
t(m)>=p_i(i)& t(m)<p_i(i+1)
If you print the first part (t(m)>=p_i(i)) it is okay, but check the other part and you'll notice the error. Maybe you can print all your results moving your increment value (+1) and prevent it from exceeding 1 to 51.

Use of Logical Masks

I working on a homework assignment and trying to solve the following problem:
Here is the code I have so far:
function [ ] = Activity45( Time )
%Homework 4
%Activity 4.5
t=Time;
A=[0:0.1:t];
B=3*exp(-(A/3)).*sin(pi.*A);
C=(B>0);
plot(A,B(C))
end
So I am trying to use a mask to extract the data from Matrix B in Matrix C. But I do not know how to match the data up between A and C, to then use plot().
Any help?
With plot(A(C), B(C)) you don't get the intended curve because you don't have values equal to zero. Instead the last two points to the left and right are connected with a line above 0. The right way would be to set the value on the Y-Axis to zero.
B(~C)=0;
plot(A,B);
For future formulas, it might be a good idea to use variable names matching the variable names in your formulas.

Append legends. Whats wrong with my code?

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:

Subscripted assignment dimension mismatch

here is the code listing and i got the above mentiond error at line nests(r,c)=nests(r,c)+stepsize.*randn(size(nests(r,c))); please let me now what is wrong with my code as i m new to matlab
for r = 1:numb_of_nest % for each particle
for c = 1:4
u=randn(size(nests(r,c)))*sigma;
v=randn(size(nests(r,c)));
step=u./abs(v).^(1/beta);
nests(r,c)=nests(r,c)+stepsize.*randn(size(nests(r,c)));
% Apply simple bounds/limits
ns_tmp=nests(r,c);
I=ns_tmp<Lb(c);
ns_tmp(I)=Lb(I);
% Apply the upper bounds
J=ns_tmp>Ub(c);
ns_tmp(J)=Ub(J);
% Update this new move
nests(r,c)=ns_tmp;
end
end
This error happens when you assign a value of some dimension m x n to a subscripted variable of different dimension.
In your case, assuming nests has no third dimension, you're assigning to a scalar (1x1) variable. This only works if the value you're trying to assign also is a scalar. Since you get the error, it probably isn't. The only place where your dimensions can be non-scalar is stepsize, so to fix this error, make sure stepsize is a scalar value.
According to the definition you gave in an earlier comment (stepsize=0.01*step.*(nests(r,c)-best);), this problem translates to make sure best is a scalar value. Possibly by subscripting, I can't tell you exactly how since I don't know what best is.
step=u./abs(v).^(1/beta);
nests(r,c)=nests(r,c)+stepsize.*randn(size(nests(r,c)));
Here you're assigning a value to the variable step, but then using a different variable called stepsize that hasn't been assigned a value anywhere in this code. Is this intentional? If not, stepsize is probably some leftover variable from previous code which is messing up the dimensions and giving you this error.
In addition to the above, is nests an ordinary two-dimensional matrix in your code? If so, taking size(nests(r,c)) every time is unnecessary - since you're giving two subscripts, the result is only going to be 1 all the time. Or is nests a cell array perhaps? In that case, you might want to index using curly braces { } instead of ordinary parantheses, to get the size of the matrix that's sitting inside the cell.

Concatenate equivalent in MATLAB for a single value

I am trying to use MATLAB in order to generate a variable whose elements are either 0 or 1. I want to define this variable using some kind of concatenation (equivalent of Java string append) so that I can add as many 0's and 1's according to some upper limit.
I can only think of using a for loop to append values to an existing variable. Something like
variable=1;
for i=1:N
if ( i%2==0)
variable = variable.append('0')
else
variable = variable.append('1')
i=i+1;
end
Is there a better way to do this?
In MATLAB, you can almost always avoid a loop by treating arrays in a vectorized way.
The result of pseudo-code you provided can be obtained in a single line as:
variable = mod((1:N),2);
The above line generates a row vector [1,2,...,N] (with the code (1:N), use (1:N)' if you need a column vector) and the mod function (as most MATLAB functions) is applied to each element when it receives an array.
That's not valid Matlab code:
The % indicates the start of a comment, hence introducing a syntax error.
There is no append method (at least not for arrays).
Theres no need to increment the index in a for loop.
Aside of that it's a bad idea to have Matlab "grow" variables, as memory needs to be reallocated at each time, slowing it down considerably. The correct approach is:
variable=zeros(N,1);
for i=1:N
variable(i)=mod(i,2);
end
If you really do want to grow variables (some times it is inevitable) you can use this:
variable=[variable;1];
Use ; for appending rows, use , for appending columns (does the same as vertcat and horzcat). Use cat if you have more than 2 dimensions in your array.