Failed to plot graph of two arrays in Octave - arrays

I have created two arrays in octave using a for loop and I want to create a graph using the data of the two arrays. But it showed an error " invalid value for array property "xdata"" and displayed an empty graph.
for i=1:16
x=1+(10^6)*2
h{i}=1/(10.^i)
fdd1{i}=(sin(1+h{i})-sin(1))/h{i}
error_f1{i}=fdd1{i}-cos(1)
endfor
**fplot(loglog(h,error_f1));**
Am I making mistakes in plotting the graph? May I know how to solve this problem?

Yes, you are doing all the possible mistakes in that snippet.
your variables h and error_f are cell arrays. The function loglog takes numeric arrays. I believe your specific error comes from there. You can convert them with cell2mat as in loglog (cell2mat (h), cell2mat (error_f1)) but I would argue that would still be incorrect since you should have never created a cell array in the first place (see point 4).
your data has non-positive values which you can't plot with logarithmic scale.
the fplot function takes a function handle as argument. Why are you passing a figure handle (the output of loglog) to it?
Octave is a language designed around vectorized operations. It's syntax has a strong emphasis and you will suffer if you don't. You should not have a for loop for this. Just remove your indexing and make your multiplication and division element-wise. This also fixes problem 1 since you will end up with a numeric array
r = 1:16;
x = 1 + (10^6)*2;
h = 1 ./ (10.^r);
fdd1 = (sin (1+h) - sin (1)) ./ h;
error_f1 = fdd1 - cos(1);
Rule of thumb in Octave: if you ever see a for loop, chances are you are doing it wrong.

Related

How to use .* in MATLAB multiplication?

I am trying to visualize the probability distribution function of Rayleigh distribution by implementing it myself in MATLAB, instead of using the inbuilt raylpdf function.
PDF of Rayleigh distribution :
This is my attempt:
function pdf = rayleigh_pdf(x)
exp_term = -1*power(x,2)/(2*std(x))
pdf = (x*exp(exp_term))/std(x)
end
But when I try to run it I get an error:
x = linspace(-10,10,100);
plot(x,rayleigh_pdf(x))
Error:
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To perform elementwise
multiplication, use '.*'.
I am not sure why I am getting this error. Where should I use .*? And why is it required?
The dot-before-operator allows one to do element-wise operations instead of the default matrix operations. If you write your code without dots, chances are high that you'll either run into dimension errors (because you're trying to do matrix multiplication with non-matching dimensions for instance), or get very weird results due to automated broadcasting, making you end up with matrices in sizes you hadn't anticipated.
function pdf = rayleigh_pdf(x)
exp_term = -x.^2./(2.*std(x).^2);
pdf = (x.*exp(exp_term))./(std(x).^2)
end
Two small things: sigma-squared usually denotes variance, i.e. standard deviation squared. So either use std(x).^2 or var(x).
Instead of writing the very verbose power(x,2) operation, you can simply use .^ to obtain the element wise power.
Note that some of the dots are superfluous, such as when you're sure that you are dealing with integers (also known as 1 -by- 1 matrices in MATLAB). You can thus write the following, which is equivalent:
function pdf = rayleigh_pdf(x)
exp_term = -x.^2/(2*std(x)^2);
pdf = (x.*exp(exp_term))/(std(x)^2)
end
i.e. dots are only required when working on arrays, x and exp_term here, and not on scalars like 2 or std(x).

Why [1:2] != Array[1:2]

I am learning Julia following the Wikibook, but I don't understand why the following two commands give different results:
julia> [1:2]
1-element Array{UnitRange{Int64},1}:
1:2
julia> Array[1:2]
1-element Array{Array,1}:
[1,2]
Apologies if there is an explanation I haven't seen in the Wikibook, I have looked briefly but didn't find one.
Type[a] runs convert on the elements, and there is a simple conversion between a Range to an Array (collect). So Array[1:2] converts 1:2 to an array, and then makes an array of objects like that. This is the same thing as why Float64[1;2;3] is an array of Float64.
These previous parts answer answered the wrong thing. Oops...
a:b is not an array, it's a UnitRange. Why would you create an array for A = a:b? It only takes two numbers to store it, and you can calculate A[i] basically for free for any i. Using an array would take an amount of memory which is proportional to the b-a, and thus for larger arrays would take a lot of time to allocate, whereas allocation for UnitRange is essentially free.
These kinds of types in Julia are known as lazy iterators. LinSpace is another. Another interesting set of types are the special matrix types: why use more than an array to store a Diagonal? The UniformScaling operator acts as the identity matrix while only storing one value (it's scale) to make A-kI efficient.
Since Julia has a robust type system, there is no reason to make all of these things arrays. Instead, you can make them a specialized type which will act (*, +, etc.) and index like an array, but actually aren't. This will make them take less memory and be faster. If you ever need the array, just call collect(A) or full(A).
I realized that you posted something a little more specific. The reason here is that Array[1:2] calls the getindex function for an array. This getindex function has a special dispatch on a Range so that way it "acts like it's indexed by an array" (see the discussion from earlier). So that's "special-cased", but in actuality it just has dispatches to act like an array just like it does with every other function. [A] gives an array of typeof(A) no matter what A is, so there's no magic here.

MATLAB sum over all elements of array valued expression

So I've been wondering about this for a while now. Summing up over some array variable A is as easy as
sum(A(:))
% or
sum(...sum(sum(A,n),n-2)...,1) % where n is the dimension of A
However once it gets to expressions the (:) doesn't work anymore, like
sum((A-2*A)(:))
is no valid matlab syntax, instead we need to write
foo = A-2*A;
sum(foo(:))
%or the one liner
sum(sum(...sum(A-2*A,n)...,2),1) % n is the dimension of A
The one liner above will only work, if the dimension of A is fixed which, depending on what you are doing, may not necessary be the case. The downside of the two lines is, that foo will be kept in memory until you run clear foo or may not even be possible depending on the size of A and what else is in your workspace.
Is there a general way to circumvent this issue and sum up all elements of an array valued expression in a single line / without creating temporal variables? Something like sum(A-2*A,'-all')?
Edit: It differes from How can I index a MATLAB array returned by a function without first assigning it to a local variable?, as it doesn't concern general (nor specific) indexing of array valued expressions or return values, but rather the summation over each possible index.
While it is possible to solve my problem with the answer given in the link, gnovice says himself that using subref is a rather ugly solution. Further Andras Deak posted a much cleaner way of doing this in the comments below.
While the answers to the linked duplicate can indeed be applied to your problem, the narrower scope of your question allows us to give a much simpler solution than the answers provided there.
You can sum all the elements in an expression (including the return value of a function) by reshaping your array first to 1d:
sum(reshape(A-2*A,1,[]))
%or even sum(reshape(magic(3),1,[]))
This will reshape your array-valued expression to size [1, N] where N is inferred from the size of the array, i.e. numel(A-2*A) (but the above syntax of reshape will compute the missing dimension for you, no need to evaluate your expression twice). Then a single call to sum will sum all the elements, as needed.
The actual case where you have to resort to something like this is when a function returns an array with an unknown number of dimensions, and you want to use its sum in an anonymous function (making temporary variables unavailable):
fun = #() rand(2*ones(1,randi(10))); %function returning random 2 x 2 x ... x 2 array with randi(10) dimensions
sumfun = #(A) sum(reshape(A,1,[]));
sumfun(fun()) %use it

What does a.{X} mean in OCaml?

I'm currently trying to port some OCaml to F#. I'm "in at the deep end" with OCaml and my F# is a bit rusty.
Anyway, the OCaml code builds fine in the OCaml compiler, but (not surprisingly) gives a load of errors in the F# compiler even with ML compatibility switched on. Some of the errors look to be reserved words, but the bulk of the errors are complaining about the .{ in lines such as:
m.(a).(b) <- w.{a + b * c};
a,b,c are integers.
I've done a lot of searching through OCaml websites, Stackoverflow, the English translation of the French O'Reilly book, etc. and cannot find anything like this. Of course it doesn't help that most search facilities have problems with punctuation characters! Yes I've found references to . being used to refer to record members, and { } being used to define records, but both together? From the usage, I assume it is some kind of associative or sparse array?
What does this syntax mean? What is the closest F# equivalent?
There is a pdf of the oCaml documentation/manual available here:
http://caml.inria.fr/distrib/ocaml-3.12/ocaml-3.12-refman.pdf
On page 496 (toward the bottom of the page), it says of generic arrays and their get method:
val get : (’a, ’b, ’c) t -> int array -> ’a
Read an element of a generic big array. Genarray.get a [|i1; ...; iN|] returns
the element of a whose coordinates are i1 in the first dimension, i2 in the second
dimension, . . ., iN in the N-th dimension.
If a has C layout, the coordinates must be greater or equal than 0 and strictly less than
the corresponding dimensions of a. If a has Fortran layout, the coordinates must be
greater or equal than 1 and less or equal than the corresponding dimensions of a. Raise
Invalid_argument if the array a does not have exactly N dimensions, or if the
coordinates are outside the array bounds.
If N > 3, alternate syntax is provided: you can write a.{i1, i2, ..., iN} instead of
Genarray.get a [|i1; ...; iN|]. (The syntax a.{...} with one, two or three
coordinates is reserved for accessing one-, two- and three-dimensional arrays as
described below.)
Further, it says (specifically about one dimensional arrays):
val get : (’a, ’b, ’c) t -> int -> ’a
Array1.get a x, or alternatively a.{x}, returns the element of a at index x. x must
be greater or equal than 0 and strictly less than Array1.dim a if a has C layout. If a
has Fortran layout, x must be greater or equal than 1 and less or equal than
Array1.dim a. Otherwise, Invalid_argument is raised.
In F#, you can access array elements using the Array.get method as well. But, a closer syntax would be w.[a + b * c]. In short, in F#, use [] instead of {}.

How can I use any() on a multidimensional array?

I'm testing an arbitrarily-large, arbitrarily-dimensioned array of logicals, and I'd like to find out if any one or more of them are true. any() only works on a single dimension at a time, as does sum(). I know that I could test the number of dimensions and repeat any() until I get a single answer, but I'd like a quicker, and frankly, more-elegant, approach.
Ideas?
I'm running 2009a (R17, in the old parlance, I think).
If your data is in a matrix A, try this:
anyAreTrue = any(A(:));
EDIT: To explain a bit more for anyone not familiar with the syntax, A(:) uses the colon operator to take the entire contents of the array A, no matter what the dimensions, and reshape them into a single column vector (of size numel(A)-by-1). Only one call to ANY is needed to operate on the resulting column vector.
As pointed out, the correct solution is to reshape the result into a vector. Then any will give the desired result. Thus,
any(A(:))
gives the global result, true if any of numel(A) elements were true. You could also have used
any(reshape(A,[],1))
which uses the reshape operator explicitly. If you don't wish to do the extra step of converting your matrices into vectors to apply any, then another approach is to write a function of your own. For example, here is a function that would do it for you:
======================
function result = myany(A)
% determines if any element at all in A was non-zero
result = any(A(:));
======================
Save this as an m-file on your search path. The beauty of MATLAB (true for any programming language) is it is fully extensible. If there is some capability that you wish it had, just write a little idiom that does it. If you do this often enough, you will have customized the environment to fit your needs.

Resources