Problems with matrix dimension - Python - python-3.6

I am trying to get matrix T in python and don't know what my mistake is. This is my code:
c=dx/L
s=dy/L
cc=c**2
ss=s**2
cs=c*s
T = np.matrix( ((cc, cs,-cc,-cs),
(cs, ss,-cs,-ss),
(-cc,-cs, cc, cs),
(-cs,-ss, cs, ss))
The values that are given are dx, dy and L. If I want to run the script it just says:
"..../miniconda3/envs/myenv/lib/python3.6/site-packages/numpy/matrixlib/defmatrix.py", line 240, in __new__
raise ValueError("matrix must be 2-dimensional")
ValueError: matrix must be 2-dimensional
Can anyone of you help me? I have no idea why the matrix should not be 2-dimensional.
Thanks

Try to make T as an array:
T = np.array( ((cc, cs,-cc,-cs),
(cs, ss,-cs,-ss),
(-cc,-cs, cc, cs),
(-cs,-ss, cs, ss)) )
Matrixes in numpy module are only 2-dimensional, but arrays are N-dimensional.

Related

In Julia Flux, I keep getting the error LoadError: Mutating arrays is not supported, but I don't see where I am mutating an array

I am new to Julia and for some reason I can't get this very simple code to work. No matter what I try, I get the error LoadError: Mutating arrays is not supported. I understand that this error occurs when I mutate an array during the course of optimization so that the code is no longer differentiable. I clearly do not understand Julia enough to see where I am doing this.
If it helps the error seems to be occurring in the line for d in dataset.
using Statistics
using Flux: onehotbatch, onehot, onecold, crossentropy, throttle
using Flux
using Base.Iterators:repeated
using Plots:heatmap
using ImageView:imshow
images = Flux.Data.MNIST.images()[1:10]
labels = Flux.Data.MNIST.labels()[1:10]
heatmap(images[4], color=:grays, aspect_ratio=1)
X = float.(reshape.(images, :))
encode(x) = onehot(x, 0:9)
Y = encode.(labels)
m = Chain(Dense(28^2, 32, relu), Dense(32, 10), softmax)
loss(x, y) = crossentropy(m(x), y)
opt = ADAM()
accuracy(x, y) = mean(onecold(m(x)) .== onecold(y))
dataset = zip(X, Y)
print(size(X))
evalcb = () -> #show(loss(X, Y))
print("Training...")
# Flux.train!(loss, params(m), dataset, opt, cb=throttle(evalcb, 5));
for d in dataset
print(d[2])
gs = gradient(params(m)) do
l = loss(d...)
end
update!(opt, params(m), gs)
end
It looks like I did have an old version of Flux (but not that old). I had to uninstall and reinstall Julia to install the new version of Flux.

Building a recursion function for LU decomposition in Julia

I am very new to Julia and tried troubleshooting some code I wrote for a recursive LU decomposition.
This is all of my code:
`using LinearAlgebra
function recurse_lu(A)
n=size(A)[1]
L=zeros(n,n)
U=zeros(n,n)
k=n/2
convert(Int, k)
A11=A[1:(k),1:(k)]
A12=A[1:(k),(k+1):n]
A21=A[(k+1):n,1:(k)]
A22=A[(k+1):n,(k+1):n]
if n>2
L11,U11=recurse_lu(A11)
L12=zeros(size(A11)[1],size(A11)[1])
U21=zeros(size(A11)[1],size(A11)[1])
U12=inv(L11)*A12
L21=inv(U11)*A21
L22,U22=recurse_lu(A22-L21*U12)
else
L11=1
L21=A21/A11
L22=1
L12=0
U21=0
U12=A12
U22=A22-L21*A12
U11=A11
end
L[1:(k),1:(k)]=L11
L[1:(k),(k+1):n]=L12
L[(k)+1:n,1:(k)]=L21
L[(k)+1:n,(k+1):n]=L22
U[1:(k),1:(k)]=U11
U[1:(k),(k+1):n]=U12
U[(k+1):n,1:(k)]=U21
U[(k+1):n,(k+1):n]=U22
return L,U
end`
This runs into
ArgumentError: invalid index: 1.0 of type Float64 when I try to compute the function for a matrix. I would really appreciate any tips for the future as well as how to resolve this. I am guessing I am working with the wrong variable type as some point, but Julia doesn't let you know where exactly the problem is.
Thanks a lot.
The error is because you try to index an array with a floating point number, example:
julia> x = [1, 2, 3]; x[1.0]
ERROR: ArgumentError: invalid index: 1.0 of type Float64
It looks like it origins from these two lines:
k=n/2
convert(Int, k)
which probably should be
k=n/2
k = convert(Int, k)
Alternatively you can use integer division directly:
k = div(n, 2) # or n รท 2
which will return an Int which you can index with.

Why do i get this error - MATLAB

I have the image and the vector
a = imread('Lena.tiff');
v = [0,2,5,8,10,12,15,20,25];
and this M-file
function y = Funks(I, gama, c)
[m n] = size(I);
for i=1:m
for j=1:n
J(i, j) = (I(i, j) ^ gama) * c;
end
end
y = J;
imshow(y);
when I'm trying to do this:
f = Funks(a,v,2)
I am getting this error:
??? Error using ==> mpower
Integers can only be combined with integers of the same class, or scalar doubles.
Error in ==> Funks at 5
J(i, j) = (I(i, j) ^ gama) * c;
Can anybody help me, with this please?
The error is caused because you're trying to raise a number to a vector power. Translated (i.e. replacing formal arguments with actual arguments in the function call), it would be something like:
J(i, j) = (a(i, j) ^ [0,2,5,8,10,12,15,20,25]) * 2
Element-wise power .^ won't work either, because you'll try to "stuck" a vector into a scalar container.
Later edit: If you want to apply each gamma to your image, maybe this loop is more intuitive (though not the most efficient):
a = imread('Lena.tiff'); % Pics or GTFO
v = [0,2,5,8,10,12,15,20,25]; % Gamma (ar)ray -- this will burn any picture
f = cell(1, numel(v)); % Prepare container for your results
for k=1:numel(v)
f{k} = Funks(a, v(k), 2); % Save result from your function
end;
% (Afterwards you use cell array f for further processing)
Or you may take a look at the other (more efficient if maybe not clearer) solutions posted here.
Later(er?) edit: If your tiff file is CYMK, then the result of imread is a MxNx4 color matrix, which must be handled differently than usual (because it 3-dimensional).
There are two ways I would follow:
1) arrayfun
results = arrayfun(#(i) I(:).^gama(i)*c,1:numel(gama),'UniformOutput',false);
J = cellfun(#(x) reshape(x,size(I)),results,'UniformOutput',false);
2) bsxfun
results = bsxfun(#power,I(:),gama)*c;
results = num2cell(results,1);
J = cellfun(#(x) reshape(x,size(I)),results,'UniformOutput',false);
What you're trying to do makes no sense mathematically. You're trying to assign a vector to a number. Your problem is not the MATLAB programming, it's in the definition of what you're trying to do.
If you're trying to produce several images J, each of which corresponds to a certain gamma applied to the image, you should do it as follows:
function J = Funks(I, gama, c)
[m n] = size(I);
% get the number of images to produce
k = length(gama);
% Pre-allocate the output
J = zeros(m,n,k);
for i=1:m
for j=1:n
J(i, j, :) = (I(i, j) .^ gama) * c;
end
end
In the end you will get images J(:,:,1), J(:,:,2), etc.
If this is not what you want to do, then figure out your equations first.

Division in prolog

I'm trying to define the division in prolog using the remainder theorem and the well-ordering principle.
I've got thus far:
less(0, s(0)).
less(0, s(B)) :- less(0, B).
less(s(A), s(s(B))) :- less(A, s(B)).
add(A,0,A) :- nat(A).
add(A,s(B),s(C)) :- add(A,B,C). % add(A,B+1,C+1) = add(A,B,C)
add2(A,0,A).
add2(A,s(B),s(C)) :- add2(A,B,C). % add(A,B+1,C+1) = add(A,B,C)
times(A,0,0).
times(A,s(B),X) :- times(A,B,X1),
add(A,X1,X).
eq(0,0).
eq(s(A), s(B)) :- eq(A, B).
% A / B = Q (R) => A = B * Q + R
div(A, B, Q, R) :- less(R, B), eq(A, add(times(Q, R), R)).
But the definition of div is somehow wrong. Could someone please give me a hint?
PS: I shouldn't be using eq, but I couldn't get is or = to work.
In SWI-Prolog, you can try ?- gtrace, your_goal. to use the graphical tracer and see what goes wrong. Instead of eq(A, add(times(Q, R), R)), you should write for example: times(Q, R, T), add(T, R, A), since you want to use the "times/3" and "add/3" predicates, instead of just calling the "eq/2" predicate with a compound term consisting of "add/2" and "times/2" as its second argument. There are other problems with the code as well, for example, the definition of nat/1 is missing, but I hope this helps somewhat.

??? Error using ==> plot - conversion to double from sym is not possible

I'm having some problems with my code. Here it is:
lambdaz = 1.2;
n = 24;
mu = 0.00055e9;
lambda = sym('lambda','clear');
W = (((2.*mu)./n.^2)).*((lambda.^n)+(lambdaz.^n)+((lambda.^-n).*(lambdaz.^-n))-3);
dW_dlambda = diff(W, lambda);
W2=(((2.*mu)./n.^2).*(lambda.^n))+(((2.*mu)./n.^2).*(lambdaz.^n))+(((2.*mu)./n.^2).*((lambda.^-n).*(lambdaz.^-n)))-(3.*((2.*mu)./n.^2))
dW2_dlambda=diff(W2,lambda)
x=((((lambda.^2).*(lambdaz))-1).^-1).*(dW_dlambda);
x2=((((lambda.^2).*(lambdaz))-1).^-1).*(dW2_dlambda)
P2 = int(x2,lambda)
P=int(x,lambda);
P=(0:1000:26700)
plot(lambda,P)
When I try to plot lambda against P I get the "conversion to double from sym is not possible" error message. I'm not particularly fantastic at Matlab so any help would be gratefully received!
The plot function only works for numeric inputs. Both lambda and P are symbolic expressions (at least before overwrote P by setting it equal to a vector after the integration) that cannot be directly converted to to floating point. You get the same error if try to something like double(sym('exp(x)')). You have two options. The first is the ezplot function in the Symbolic Toolbox:
...
P = int(x,lambda);
ezplot(P,[-5 5]); % Plot's P from lambda = -5 to lambda = 5
Or you can use the subs function:
...
P = int(x,lambda);
lambda = -5:0.01:5;
plot(lambda,real(subs(P,'lambda',lambda)))
axis([lambda(1) lambda(end) -1e15 1e15])
I used real to suppress a warning for negative values of lambda.

Resources