issue with iterating over one ith step in a for loop and using that one value to plug into another equation before returning to the next ith step - matlab

I am working on a long code involving neutron stars in Matlab and I have run into a snag. All I want to do is create a for loop in which I solve an equation for r. Before moving to the next ith iteration, I need to take that single solved value for r and plug it into another equation to solve for b. Then it can go back to the beginning and do the two equations over again with the next ith step. I seem to be having great difficulty programming this and I think it has something to do with how I am defining my variables. Here is that part of the code:
clear all;
p=input('TauesNtm1 Value?');
n=input('Nt Value?');
t=input('Taues1 Value?');
for i=(2:1:((n/2)-2)/1);
r(i)=.5*Log10((2*p)^((1 - 2*(i - 2))/(n - 4))*(t/2)^((2*(i - 2))/(n - 4)))+(i - 2)*(((n - 4)*p-2*p-.5*t)/(n - 4));
b(r(i))=.434294*(.190352 + 2.20509566529930*r+1.379117301391070*r^2-0.481593138241581*r^3- 0.2311271889879584*r^4+0.500820485853822*r^5-0.269537234996903*r^6-0.20063340749777*r^7+0.475894136618535*r^8-0.2831206627297433*r^9-0.2328164535174437*r^10+0.585886001688777*r^11-0.3690986055298708*r^12-0.310009361710399*r^13+0.817684785462915*r^14-0.537360306829214*r^15-0.447280339896678*r^16+1.229551315307617*r^17-0.836592197418212*r^18-0.679642677307128*r^19+1.942584991455078*r^20);
end
Any ideas as to what I am doing wrong?

You have two mistakes. First, you can not reference b using r, because r is real and arrays can only be referenced by integer values. You need to do it like that:
b(i) = ...
and not like that
b(r(i)) = ...
Another thing is, in the computation of b you use r, which is a vector. If I understand correctly, you only want the formula of b to depend on r(i). You need to change r to r(i). This is the resulting code:
for i=(2:1:((n/2)-2)/1);
r(i)=.5*log10((2*p)^((1 - 2*(i - 2))/(n - 4))*(t/2)^((2*(i - 2))/(n - 4)))+(i - 2)*(((n - 4)*p-2*p-.5*t)/(n - 4));
b(i)=.434294*(.190352 + 2.20509566529930*r(i)+1.379117301391070*r(i)^2-0.481593138241581*r(i)^3- 0.2311271889879584*r(i)^4+0.500820485853822*r(i)^5-0.269537234996903*r(i)^6-0.20063340749777*r(i)^7+0.475894136618535*r(i)^8-0.2831206627297433*r(i)^9-0.2328164535174437*r(i)^10+0.585886001688777*r(i)^11-0.3690986055298708*r(i)^12-0.310009361710399*r(i)^13+0.817684785462915*r(i)^14-0.537360306829214*r(i)^15-0.447280339896678*r(i)^16+1.229551315307617*r(i)^17-0.836592197418212*r(i)^18-0.679642677307128*r(i)^19+1.942584991455078*r(i)^20);
end

Related

Get solution of an lineal ordinary differential equation without constants

I made an algorithm for solving an specific IVP. I get the solution with the function dsolve() in MatLab, but I don't want to get the solution in terms of the constants because I'm gonna replace the solution in my IVP.
For example, when I solve dsolve('Dy = x + y','x) ' I get C12*exp(x) - x - 1 but I only want to obtain exp(x) - x - 1. It's very straightforward to chop out the C12 by converting the sym to string, but I don't know if I try with a different function will it have more constants and only 'chopping' the first characters will work. So...
Is there a way to get the output of dsolve() without the constants?
You can simply add an initial condition and you'll have an output without constants.
Like dsolve('Dy = x + y','y(0)=0','x')

What does this line of Matlab code mean? [duplicate]

This question already has answers here:
The meaning of colon operator in MATLAB
(2 answers)
Closed 6 years ago.
I'm new to Matlab, and I'm trying to unscrabble the code here. In particular, I'm wondering what this line does:
ti = (Series{1}(2, i) - L*Dt):Dt:(Series{1}(2, i)-Dt);
In particular, what does the colon do? I found this explanation:
But to me this doesn't tell me what it's doing here. Similarly, I'm not even clear on what Series{1}(2, i) - L*Dt produces. I get that normally the answer would be 'try it out', but I don't have access to Matlab and so would appreciate any comments or advice.
Thank you.
Curly braces are used for cell arrays, a data-structure that can hold any type. In this case, I think it's a safe guess that Series{1} contains a matrix, so Series{1}(2,i) is just a specific entry. Writing this out step-by-step might be the easiest to understand:
A = Series{1} % get the matrix
t0 = A(2,i) - L*Dt;
tN = A(2, i) - Dt;
ti = t0:Dt:tN; % create a time-series from time t0 to tN, with step-size Dt
in the linked code it says Each cell is a 2xT matrix. First row contains the values and the second row contains SORTED time stamps. The first time series is the target time series which is predicted.
Series{1}(2, i) fetches the i-th time stamp ((2,i) means), in the first time series ({1} means) (which i guess is used as a reference frame), and let's think that it is a certain given number T0.
The second step of the code is to establish a time array, starting from T0 - L*Dt and stops at T0 - *Dt. The length of each increment is Dt.
It's same as The meaning of colon operator in MATLAB as pointed out by #TroyHaskin . But i think it's the cell array that makes it less easy to understand.

First Derivative filter Matlab

I have recently been tasked with using a first derivative filter on an image of myself. The instructor said that I should first fix the value of y and preform f(x+1) - f(x) on the rows and then fix the new "X" values and preform f(y+1)-f(y) on the columns.
Note: I have been asked to do this task manually, not using filter2() or any other programmed function, so please do not suggest that I use filter2() or similar. Thanks!
I tried calling up all the pixels and subtracting each successive one by doing
fid = fopen('image.raw')
myimage = fread(fid,[512 683], '*int8')
fclose(fid)
imsz = size(myimage)
x = imsz(1)
for I = 1:512
for J = 1:683
X(I) - X(I-1) = XX
But it doesnt seem to work, and I dont quite understand why. If you could help me, or point me in the right direction, I would be very appreciative.
First of all, your code is syntatically incorrect:
There is no end statement to any of your loops, and besides, you don't even need loops here.
You seem to read your image into the variable myimage, but you're using an undefined variable X when attempting to calculate the derivative.
The order of your assignment statements is reversed. The variable you wish to assign to should be written in the left hand part of the assignement.
I strongly suggest that you read online tutorials and get yourself familiar with MATLAB basics before taking on more complicated tasks.
As to your specific problem:
MATLAB encourages vectorized operations, i.e operations on entire arrays (vectors or matrices) at once. To subtract adjacent values in an array, what you're basically doing is subtracting two arrays, shifted by one element with respect to each other. For one dimensional arrays, that would translate in MATLAB to:
a(2:end) - a(1:end-1)
where a is your array. The end keyword specifies the last index in the array.
To compute the derivative of an image (a 2-D matrix), you need to decide along which axis you want to perform that operation. To approximate the derivate along the y-axis, do this:
X(2:end, :) - X(1:end-1, :)
You can verify that this gives you the same result as diff(X, 1) (or simply diff(X)). To compute the approximate derivative along the x-axis, which is equivalent to diff(X, 2), do this:
X(:, 2:end) - X(:, 1:end-1)
The colon (:) is the same as writing 1:end as the array subscript for the corresponding dimension.
If your filtered image is div then
for Y = 1:682
for X = 1:511
div(X, Y) = myimage(X + 1, Y + 1) - myimage(X,Y);
end
end
Remember the last row and the last column are not filtered!

MATLAB - vector script

I have recently started learning MatLab, and wrote the following script today as part of my practice to see how we can generate a vector:
x = [];
n = 4;
for i = i:n
x = [x,i^2];
end
x
When I run this script I get what I expect, namely the following vector:
x = 0 1 4 9 16
However, if I run the script a second time right afterwards I only get the following output:
x = 16
What is the reason for this? How come I only get the last vector entry as output the second time I run the script, and not the vector in its entirety? If anyone can explain this to me, I would greatly appreciate it.
Beginning with a fresh workspace, i will simply be the complex number 1i (as in x^2=-1). I imagine you got this warning on the first run:
Warning: Colon operands must be real scalars.
So the for statement basically loops over for i = real(1i):4. Note that real(1i)=0.
When you rerun the script again with the variables already initialized (assuming you didn't clear the workspace), i will refer to a variable containing the last value of 4, shadowing the builtin function i with the same name, and the for-loop executes:
x=[];
for i=4:4
x = [x, i^2]
end
which iterates only one time, thus you end up with x=16
you forget to initialize i.
after first execution i is 4 and remains 4.
then you initialize x as an empty vector but because i is 4 the loop runs only once.
clear your workspace and inspect it before and after first execution.
Is it possibly a simple typo?
for i = i:n
and should actually mean
for i = 1:n
as i is (probably) uninitialized in the first run, and therefore 0, it works just fine.
The second time, i is still n (=4), and only runs once.
Also, as a performance-tip: in every iteration of your loop you increase the size of your vector, the more efficient (and more matlaboid) way would be to create the vector with the basevalues first, for example with
x = 1:n
and then square each value by
x = x^2
In Matlab, using vector-operations (or matrix-operations on higher dimensions) should be prefered over iterative loop approaches, as it gives matlab the opportunity to do optimised operations. It is also often more readable that way.

matlab matrices and fold list

i have two problems in mathematica and want to do them in matlab:
measure := RandomReal[] - 0.5
m = 10000;
data = Table[measure, {m}];
fig1 = ListPlot[data, PlotStyle -> {PointSize[0.015]}]
Histogram[data]
matlab:
measure =# (m) rand(1,m)-0.5
m=10000;
for i=1:m
data(:,i)=measure(:,i);
end
figure(1)
plot(data,'b.','MarkerSize',0.015)
figure(2)
hist(data)
And it gives me :
??? The following error occurred
converting from function_handle to
double: Error using ==> double
If i do :
measure =rand()-0.5
m=10000;
data=rand(1,m)-0.5
then, i get the right results in plot1 but in plot 2 the y=axis is wrong.
Also, if i have this in mathematica :
steps[m_] := Table[2 RandomInteger[] - 1, {m}]
steps[20]
Walk1D[n_] := FoldList[Plus, 0, steps[n]]
LastPoint1D[n_] := Fold[Plus, 0, steps[n]]
ListPlot[Walk1D[10^4]]
I did this :
steps = # (m) 2*randint(1,m,2)-1;
steps(20)
Walk1D =# (n) cumsum(0:steps(n)) --> this is ok i think
LastPointold1D= # (n) cumsum(0:steps(n))
LastPoint1D= # (n) LastPointold1D(end)-->but here i now i must take the last "folding"
Walk1D(10)
LastPoint1D(10000)
plot(Walk1D(10000),'b')
and i get an empty matrix and no plot..
Since #Itamar essentially answered your first question, here is a comment on the second one. You did it almost right. You need to define
Walk1D = # (n) cumsum(steps(n));
since cumsum is a direct analog of FoldList[Plus,0,your-list]. Then, the plot in your code works fine. Also, notice that, either in your Mathematica or Matlab code, it is not necessary to define LastPoint1D separately - in both cases, it is the last point of your generated list (vector) steps.
EDIT:
Expanding a bit on LastPoint1D: my guess is that you want it to be a last point of the walk computed by Walk1D. Therefore, it would IMO make sense to just make it a function of a generated walk (vector), that returns its last point. For example:
lastPoint1D = #(walk) (walk(end));
Then, you use it as:
walk = Walk1D(10000);
lastPoint1D(walk)
HTH
You have a few errors/mistakes translating your code to Matlab:
If I am not wrong, the line data = Table[measure, {m}]; creates m copies of measure, which in your case will create a random vector of size (1,m). If that is true, in Matlab it would simply be data = measure(m);
The function you define gets a single argument m, therefor it makes no sense using a matrix notation (the :) when calling it.
Just as a side-note, if you insert data into a matrix inside a for loop, it will run much faster if you allocate the matrix in advance, otherwise Matlab will re-allocate memory to resize the matrix in each iteration. You do this by data = zeros(1,m);.
What do you mean by "in plot 2 the y=axis is wrong"? What do you expect it to be?
EDIT
Regarding your 2nd question, it would be easier to help you if you describe in words what you want to achieve, rather than trying to read your (error producing) code. One thing which is clearly wrong is using expression like 0:steps(n), since you use m:n with two scalars m and n to produce a vector, but steps(n) produces a vector, not a scalar. You probably get an empty matrix since the first value in the vector returned by steps(n) might be -1, and 0:-1 produces an empty vector.