Declare variables in for loop for files with different number of samples (IDL) - idl-programming-language

I would like to do exactly what is explained in the answer by Jim Lewis to the post below (see link) in the case that each file contains a different number of samples. Jim states that this can be done using PTR_NEW. Any ideas how to use PTR_NEW in the loop showed in the answer?
Thanks,
Catia
How to declare variables in for loop? (IDL)

I think they mean something like:
a = ptrarr(n)
b = ptrarr(n)
c = ptrarr(n)
d = ptrarr(n)
for i = 0L, n - 1L do begin
readcol, string(i, F='(I02)') + '.dat', F='D,D', x, y
a[i] = ptr_new(x)
b[i] = ptr_new(y)
c[i] = ptr_new(x/x[0])
d[i] = ptr_new(y/y[0])
endfor
Access like this:
for i = 0L, n - 1L do begin
help, *a[i]
endfor
In this example, the size and type of x and y can vary each iteration.

Related

Julia UndefVarError on Metaprogramming

I'm trying to do a solver for equations. When I run the code the X variable appears to be undefined, but it prints out perfectly. What am I missing?
I should give the program some numbers, than operations as Macros and it should create an outer product matrix of the operations applied.
function msu()
print("Insert how many values: ")
quantity = parse(Int64, readline())
values = []
for i in 1:quantity
println("x$i")
num1 = parse(Float64, readline())
push!(values, num1)
end
println(values)
print("How many operations? ")
quantity = parse(Int64, readline())
ops = []
for i in 1:quantity
push!(ops, Meta.parse(readline()))
end
mat = zeros((quantity, quantity))
for i in 1:length(mat)
sum = 0
for j in 1:length(values)
# here begins problems, the following prints are for debugging purpose
print(length(values))
func = Meta.parse("$(ops[convert(Int64, ceil(j / quantity))]) * $(ops[convert(Int64, j % quantity)])")
print(func)
x = values[j]
println(x)
sum += eval(func)
end
mat[i] = sum
end
println(mat)
end
msu()
The original code was in Spanish, if you find any typo it's probably because I skipped a translation.

ST-HOSVD in Julia

I am trying to implement ST-HOSVD algorithm in Julia because I could not found library which contains ST-HOSVD.
See this paper in Algorithm 1 in page7.
https://people.cs.kuleuven.be/~nick.vannieuwenhoven/papers/01-STHOSVD.pdf
I cannot reproduce input (4,4,4,4) tensor by approximated tensor whose tucker rank is (2,2,2,2).
I think I have some mistake in indexes of matrix or tensor elements, but I could not locate it.
How to fix it?
If you know library of ST-HOSVD, let me know.
ST-HOSVD is really common way to reduce information. I hope the question helps many Julia user.
using TensorToolbox
function STHOSVD(A, reqrank)
N = ndims(A)
S = copy(A)
Sk = undef
Uk = []
for k = 1:N
if k == 1
Sk = tenmat(S, k)
end
Sk_svd = svd(Sk)
U1 = Sk_svd.U[ :, 1:reqrank[k] ]
V1t = Sk_svd.V[1:reqrank[k], : ]
Sigma1 = diagm( Sk_svd.S[1:reqrank[k]] )
Sk = Sigma1 * V1t
push!(Uk, U1)
end
X = ttm(Sk, Uk[1], 1)
for k=2:N
X = ttm(X, Uk[k], k)
end
return X
end
A = rand(4,4,4,4)
X = X_STHOSVD(A, [2,2,2,2])
EDIT
Here, Sk = tenmat(S, k) is mode n matricization of tensor S.
S∈R^{I_1×I_2×…×I_N}, S_k∈R^{I_k×(Π_{m≠k}^{N} I_m)}
The function is contained in TensorToolbox.jl. See "Basis" in Readme.
The definition of mode-k Matricization can be seen the paper in page 460.
It works.
I have seen 26 page in this slide
using TensorToolbox
using LinearAlgebra
using Arpack
function STHOSVD(T, reqrank)
N = ndims(T)
tensor_shape = size(T)
for i = 1 : N
T_i = tenmat(T, i)
if reqrank[i] == tensor_shape[i]
USV = svd(T_i)
else
USV = svds(T_i; nsv=reqrank[i] )[1]
end
T = ttm( T, USV.U * USV.U', i)
end
return T
end

Julia 1.0.2.1: Why is a variable changing value, without being assigned?

I am building a metaheuristic in Julia for study purpose.
The purpose is to find the best order of boxes.
1) I start with an initial order (random order) defined as. Order = InitOrder before my while loop.
2) For each iteration in the while loop I set CurrentOrder = Order
3) When the CurrentOrder is changed, Order changes too. Why does Order change value without being assigned? And how do I avoid it?
Version:
JuliaPro 1.0.2.1
Editor: Atom
while ( (time_ns()-timestart)/1.0e9 < RunLength && done == false ) #Stopping Criteria
done = true #Starting point
IterationCount = IterationCount + 1
BestCurrentValue = sum(H) #Worst case solutio
CurrentOrder = Order #(From,To)
for n1=1:N
for n2=1:N
if n1 != n2
(CurrentOrder,CopyTo) = SwapBox(CurrentOrder,n1,n2) #Swap boxes
(CurrentLayout,L) = DeltaCopy(CurrentLayout,CopyTo,CurrentOrder) #Delta Copy to minimise calculations
(TempLayout,L) = BLV(BinW,CurrentLayout,CopyTo,CurrentOrder,W,H,L) #Evalueate by BLV
if L < BestCurrentValue #check if TempLayout is better than Best Current
BestCurrentValue = L
BestCurrentOrder = CurrentOrder
BestCurrentLayout = CurrentLayout
end #if L<...
end #if n1 != n2
##############################################################################
CurrentOrder = Order
##############################################################################
end #n2 in N
end #n1 in N
if BestCurrentValue < BestValue
done = false #Look further
BestValue = BestCurrentValue
BestOrder = BestCurrentOrder
BestLayout = BestCurrentLayout
Order = BestOrder
end #if BestCurrentValue...
end #while
Your assignment NewOrder=Order does not copy any information in memory, it just says that the variable NewOrder should point to the same memory location as Order. Changing one of these variables will thus also change the other. If you want to copy a variable you could use NewOrder=deepcopy(Order)

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.

Maple: How to give values to assumptions for plotting?

So I have a simple example of what I want to do:
restart;
assume(can, real);
f := {g = x+can*x*y, t = x+x*y};
assign(f[1]); g;
can := 2;
plot3d(g, x = 0 .. 100, y = 0 .. 100);
while this works:
restart;
f := {g = x+can*x*y, t = x+x*y};
assign(f[1]);
can := 2;
plot3d(g, x = 0 .. 100, y = 0 .. 100);
But that assumptions are really important for my real life case (for some optimisations with complex numbers) so I cant just leve can not preassumed.
Why it plots nothuing for me and how to make it plot?
The expression (or procedure) to be plotted must evaluate to a numeric, floating-point quantity. And so, for your expression g, the name can must have a specific numeric value at the time any plot of g is generated.
But you can produce a sequence of 3D plots, for various values of can, and display them. You can display them all at once, overlaid. Or you can display them in an animated sequence. And you can color or shade them each differently, to give a visual cue that can is changing and different for each.
restart;
f := {g = x+can*x*y, t = x+x*y};
eval(g,f);
N:=50:
Pseq := seq(
plot3d(eval(g,f),
x=0..10,y=0..10,
color=RGB(0.5,0.5,can/(2*N)),
transparency=0.5*(can/(N+1))),
can=1 .. N):
plots:-display(Pseq, axes=box);
plots:-display([Pseq],insequence=true,axes=box);
By the way, you don't have to assign to g just for the sake of using the equation for g that appears inside f. Doing that assignment (using assign, say, like you did) makes it more awkward for you subsequently to create other equations in terms of the pure name g unless you first unassign the name g. Some people find it easier to not make the assignment to g at all for such tasks, and to simply use eval as I've done above.
Now on to your deeper problem. You create an expression containing a local, assumed name. and then later on you want to use the same expression but with the global, unassumed version of that name. You can create the expression, with it containing the global, unassumed name instead of the local, assumed name, buy performing a substitution.
restart;
assume(can, real);
f := {g = x+can*x*y, t = x+x*y};
{g = x + can~ x y, t = x + x y}
assign(f[1]);
g;
x + can~ x y
can := 2:
g;
x + can~ x y
# This fails, because g contains the local name can~
plot3d(g, x=0..100, y=0..100);
# A procedure to make the desired substitution
revert:=proc(nm::name)
local len, snm;
snm:=convert(nm,string);
len:=length(snm);
if snm[-1]="~" then
return parse(snm[1..-2]);
else return parse(nm);
end if;
end proc:
# This is the version of the expression, but with global name can
subsindets(g,`local`,revert);
x + can x y
# This should work
plot3d(subsindets(g,`local`,revert),
x=0..100,y=0..100);

Resources