Can anyone explain to me what this Script does? - matlab

This code it's an Integration method used to accept as input parameters the values from integration nodes.(Excuse my bad english)
This is part of least approach method.
function s = simpson(x,y)
n = length(x);
h = x(2)-x(1);
s = h/3*(y(1)+y(n)+4*sum(y(2:2n-1))+2*sum(y(3:2:n-2)));
I'm trying to run the code on octave online and opens a windows to insert the value of X and Y but... this is what gives to me...
error: invalid use of script /home/oo/Simpson.m in index expression
I don't know what to do, please I really needsome help!
Explain to me like you were talking to a little kid... (This is because of my lack of english skillss)
Thanks From the buttom of my hearth :3

your code is almost OK but in last line by refer to this link there was a little error so change this line as follow
s = h/3*(y(1)+y(n)+4*sum(y(2:2:n-1))+2*sum(y(3:2:n-2)));
and for test your function suppose we have two vector x=[1 2 3] and y=[2 3 4] then we type below code in command windoe
x = [1 2 3];
y = [2 3 4];
simpson(x,y)
ans=
6

Related

Matlab displayFormula has a bug when using matrices?

displayFormula("c=b*a")
syms a
displayFormula("c=b*a", a, 6)
displayFormula("c=b*a", a, [[1 2];[3 4]])
d=[[1 2];[3 4]]
displayFormula("c=b*d")
Line 1 executes fine. Line 2 is needed to permit execution of line 3. Line 4 throws an error. Line 6 executes fine and displays the entire matrix. Line 6 successful execution, which is displaying the entire matrix, suggests displayFormula can take matrices as inputs. On the other hand, Line 4 error suggests that displayFormula cannot take matrices as inputs. Line 3 demonstrates that the verbose form of displayFormula can take Ints, Floats, Doubles as arguments.
I suspect that this is just a Matlab bug, or perhaps a feature that i would like which has not been implemented, but I also wonder if I am making a mistake.
Line 4 throws the following error:
Error using displayFormula
Inconsistency between sizes of second and third arguments.
Error in bugDisplayFormulaWithMatrices (line 4)
displayFormula("c=b*a", a, [[1 2];[3 4]])
I am pretty sure the following code proves displayFormula() is buggy with matrices:
syms a b c d A Z
A = [[a b];[c d]]
a1 = 2;
mix = subs(A, a, a1)
Z = A*A
Z1 = subs(A*A,a,a1)
displayFormula('Z = A*A')
displayFormula("Z = A*A", a, a1)
The above code produces the following livescript output:
The 'Z1=' livescript result installs '2' into the display. displayFormula("AA") cannot install values into the variables. The verbose form of displayFormula("AA", a, a1) not only fails to install '2' into the display but also collapses the display completely.
One other thing we know for certain is that displayFormula() does not function as shown in the Apple documentation. Apple documentation identifies the argument of displayForumula() as a 'symstr'. But this code works fine when the argument of displayForumula() is not a symstr:
A=[[1 2];[1 4]]
displayFormula("A*A")
So my conclusion is that displayFormula() will be improved to work better with matrices, but its buggy now.

Difference between append and x = [x, element]

I've create an array X as X = [1 2 3 4 5] and I want to insert 0 at the end of it.
Is there any difference in using X = [X, 0] and X = append(X, 0)?
I didn't find anything about and I'm not sure if I can notice the difference.
Thanks in advance!
As explained in the other answer, append is part of a toolbox, and not available to everyone.
The correct way to append to a matrix, however, is
X(end+1) = 0;
This is a whole lot more efficient than X=[X,0]. The difference is that this latter form creates a new array, and copies the original one into it. The other form simply appends to the matrix, which usually doesn't require reallocation. See here for an experiment that shows the difference (read the question and my answer for both parts of the experiment).
append function is a part of Symbolic Math Toolbox. It's preferred to use [X, 0] as it is part of a core language and more likely to be understood.

How can I use of norm(a,b) in matlab if a, b are double type?

I must to use angle = atan2(norm(cross(a,b)),dot(a,b)), for calculating the angle between two vectors a,b and these are double type and norm is undefined for this type. How do I resolve this problem? I need to calculate the angle between two vectors this way.
In your comments, you have shown us how you are actually writing out the angle calculation and it is not the same as how you have put it in your post.
atan2(norm(cross(I(i,j,:),I_avg)),dot(I(i,j,:),I_avg));
I is an image you are loading in. I'm assuming it's colour because of the way you are subsetting I. Because I is a 3D matrix, doing I(i,j,:) will give you a 1 x 1 x 3 vector when in fact this has to be a 1D vector. norm does not recognize this structure which is why you're getting this error. Therefore, you need to use squeeze to remove the singleton dimensions so that this will become a 3 x 1 vector, rather than a 1 x 1 x 3 vector. As such, you need to rewrite your code so that you're doing this instead. Bear in mind that in your comments, angle is always overwritten inside the for loop, so you probably want to save the results of each pixel. With this, you probably want to create a 2D array of angles that will store these results. In other words:
I=imread('thesis.jpg');
I = double(I);
angles = zeros(m,n);
I_avg = squeeze(I_avg); %// Just in case
for i=1:m
for j=1:n
pixels = squeeze(I(i,j,:)); %// Add this statement and squeeze
angles(i,j) = atan2(norm(pixels,I_avg)),dot(pixels,I_avg)); %// Change
end
end
Minor note
MATLAB has a built-in function called angle that determines the angle from the origin to a complex number in the complex plane. It is not recommended you call your variable angle as this will unintentionally shadow over the angle function, and any other code that you create from this point onwards may rely on that actual angle function, and you will get unintended results.
Another minor note
Using i and j as loop variables is not recommended. These letters are reserved for the complex number, and this can produce unintentional results. Take a look at this question and post by Shai here - Using i and j as variables in Matlab. As such, it is suggested you use other variable names instead.
As #rayryeng has successfully answered this question, I would like to turn my post into a more general one by sharing my experience in debugging in Matlab. I hope anyone who somehow managed to find this post get more or less thinking about the habits a good programmer should have.
The question goes like: "How would I do if I get errors?"
Here's an excellent article by Eric in which he lists the rule-of-thumbs when you encounter a bug and wish to get rid of it. It's originally been cited by Stackoverflow, and that's the reason I read it.
If you still get no clue / idea how you can play with your code, see how this person does:
Pin-point the buggy line
(The number should start with 0) Make sure before running a script, you clear out any previously stored variables, including the notorious i and j's (you should never see them in any workspace). If any one is needed for the buggy code to run, save('buggy.mat','importantvar') before clear and load('buggy.mat') after clear.
By doing so, you can isolate your buggy code from anything else, which could have bad influences. For example, in a previously called script, there is a line
double = [2,4,6]; % you should never name a variable `double`
and in the next script, you have
>> e = str2num('uint8(200)')
e =
200
>> double(e)
Index exceeds matrix dimensions.
>>
>> f = single(2.36)
f =
2.3600
>> double(f)
Subscript indices must either be real positive integers or
logicals.
>>
The reason is double is no longer an inbuild function, but a user-defined variable. Too bad to pick up a name carelessly!
....anyway, let's clear the workspace and get rid of double.
>> clear
Read the error message, thoroughly.
Now let's begin with OP's problem. The original code (trimmed) goes like this -
img = imread('peppers.png');
a = img(300,200,:);
b = img(200,300,:);
d = norm(cross(a,b));
.... hence the error
Undefined function 'norm' for input arguments of type 'uint8'.
Error in untitled (line 6)
d = norm(cross(a,b));
Most beginners are only interested in the first line of the error message, which by it alone usually doesn't provide any useful help, or only in the red color, which leads to the famous question "my code does not work!"
But think twice. You still have another 2 lines unread! Error in untitled (line 6) says I'm running a script named untitled and the (first) error lies in line 6, and the code in that line is d = norm(cross(a,b));.
Now, at least you know a little more about your code - "My code d = norm(cross(a,b)); doesn't work!"
Although most likely we may also vote this kind of question to get closed, it's still much much better than a simply "It does not work!".
Now we can pin-point the buggy line
try
% this line will raise an error
d = norm(cross(a,b));
catch err
disp(err.message)
end
Look into the functions
First, make sure the inner function cross works as expected -
>> cross(a,b)
ans(:,:,1) =
0
ans(:,:,2) =
255
ans(:,:,3) =
0
>>
Good. So now we can even narrow down the error to the outer norm.
One more thing to mention. You can always find Mathworks' documentation for any in-build function, by typing "matlab function", such as "matlab norm" in Google (or any other search engine) and clicking on the first result. If you prefer, you can also type in Matlab command window doc _function_ such as doc norm and read the doc in Matlab. It's of course a pleasure of us on Stackoverflow to give you the reference by doing the same thing, but it takes a longer time because a human is, in this aspect, always slower than a search engine.
The error reads Undefined function 'norm' for input arguments of type 'uint8'.. So the input for norm should not be uint8, unsigned 8-bit integer. But what should it be?
% why `norm` "does not work"?
% this line runs perfectly well
norm(cross([1,2,3], [4,5,6]))
% so what is working?
class([1,2,3]) % so `norm` works for `double`
One thing we can do now is convert a and b to double precision. Let's try it now.
% try fixing 'uint8' error
a2 = double(a);
b2 = double(b);
whos a b % now they are double, which `norm` should work for
try
% this line will raise an error
d = norm(cross(a2,b2));
catch err
disp(err.message)
end
Now the error becomes Input must be 2-D.. What's wrong with the input?
% what is "must be 2-D" error?
size(a2) % a2 is 3-D
disp(b2) % b2 is also 3-D
This gives output in command window
ans =
1 1 3
(:,:,1) =
255
(:,:,2) =
150
(:,:,3) =
0
In OP's problem, he/she is trying to calculate something about color difference (to the best of my knowledge) which involves the angle between two color vectors in RGB space. So the vectors are needed. With imread, each pixel of the image is stored as 3 elements in the matrix, first 2 dimension being its physical position, the 3 dimension being RGB channel components. Hence pixel(200,300) with color rgb[255,150,0] is stored by us in variable b wihch is a 3-D vector.
By understanding what we need and what Matlab can do, we can combine these two points into one. We need the norm of the cross product of a and b, while the useful information (the 3 component values) is stored in the 3rd dimension. Matlab can calculate the norm of the cross product of a vector with all its information in the 1st dimension. (Here, "dimension" refers to that of the Matlab variable; a vector with 3 elements in its 1st dimension is physically a 3-D vector).
After thinking twice, we are now able to debug our code - just put all 3 elements into the 1st dimension.
% so we want the 3 elements in the 3rd dimension become in the 1st dim
a3 = squeeze(a2);
b3 = reshape(b2,numel(b2),[]);
try
d = norm(cross(a3,b3));
catch err
disp(err.message)
end
d
Bonus: If by default Matlab treats a 3-D vector as a "1-D array", then most probably the cross function has not been working correctly. Let's make a check -
>> clear
>> a = [1,2,3]
a =
1 2 3
>> b=[4,5,6]
b =
4 5 6
>> cross(a,b)
ans =
-3 6 -3
>>
The result should be the same as the one we can get by calculating by hand.
Now if we put the components into the 3rd dimension of the variable -
>> clear
>> a(1,1,:)=[1,2,3]
a(:,:,1) =
1
a(:,:,2) =
2
a(:,:,3) =
3
>> b(1,1,:)=[4,5,6]
b(:,:,1) =
4
b(:,:,2) =
5
b(:,:,3) =
6
>> cross(a,b)
ans(:,:,1) =
-3
ans(:,:,2) =
6
ans(:,:,3) =
-3
>>
.... seems OK. cross also puts the result in the 3rd dimension. In fact, Mathworks' documentation says
If A and B are vectors, then they must have a length of 3.
If A and B are matrices or multidimensional arrays, then they must
have the same size. In this case, the cross function treats A and B as
collections of three-element vectors. The function calculates the
cross product of corresponding vectors along the first array dimension
whose size equals 3.
At last, one thing is always correct to anyone who wants to do something with programming - be cautious and prudent when writing your code.

MATLAB vector element conflict.

I have been having trouble getting rid of this error. I have read several similar question, but I just must be overlooking something very simple. The following code uses ODE45. There are 3 initial conditions, and it appears to me that my function outputs 3 variables as well. However, it says:
"??? Error using ==> odearguments at 116
DBTS returns a vector of length 2, but the length of initial
conditions vector is 3. The vector returned by DBTS and the
initial conditions vector must have the same number of elements."
This is my m-file:
function dDdt=Dbts(t,i)
global p1 p2 p3 n V1 Gb Ib U
I=i(1);
X=i(2);
G=i(3);
dIdt=-(n*(I-Ib))+(U/V1);
dXdt=-(p2*X)+(p3*I);
dGdt=-(p1*G)-(X*(G-Gb))+(9.0*exp(-0.05*t));
dDdt=[dIdt;dXdt;dGdt];
This is what I put into main:
global p1 p2 p3 n V1 Gb Ib
p1=0.028735;
p2=0.0228344;
p3=.00005035;
n=.0926;
V1=12;
Gb=81;
Ib=15;
global G X I U
TT=[];
SS=[];
i0=[0 0 0];
tspan=[0 400];
[t,i]=ode45(#Dbts,tspan,i0);
At this point the error I posted above comes up. I know I must have miscalculated something here, but I just can't pinpoint it. If anyone could please help with this, I would be extremely grateful. All I have to do is plot 3 graphs when I fix this problem.
I think it's because U isn't defined:
>> size(U)
ans =
0 0
so the size of DiDt is 0x0 and consequently the output of Dbts is 2x1.

Can you give me an example of comm.FSKModulator along with it's step function?

Can you tell me how to use PSKModulator with it's step function. I was able to solve comm.PSKModulator usage like this:
>> H=comm.FSKModulator('ModulationOrder',2,'BitInput',false,'SymbolMapping','Binary','FrequencySeparation',10);
but when I try to run Step function that takes H and X as arguments (X is digital values that I would like to encode in H) I get an error.
>> X=[0 1];
>> Y=step(H,X);
Error:
Error using FSKModulator/step
Multichannel operation is not supported.
I looked through Internet but there is no much of examples as this functions are very fresh.
do you know how to set up this?
Thank you
Each column is treated as a different channel by this object. You need to send a column vector as input to the step method. In your code try using Y = step(H,X.') or change X to X = [0; 1];.