Define array of float values in Actionscript 1.0 - arrays

I am trying to make an array of 3 floats in Actionscript 1.0, but instead of incrementing the X & Y variables by 1, it just adds 1 to the end of the previous value. This has nothing to do with Flash, it is being used for an extension for a server that requires extensions in Actionscript 1.0.
var uVars = [];
uVars.X = 250;
uVars.Y = 3;
uVars.Z = 250;
uVars.X += 1;
uVars.Y += 0;
uVars.Z += 1;
trace(uVars.X);

Show us your output, please. I assume you mean "X & Z," not "X & Y."
I don't have AS1 handy, but I'm going to make a bet that the numbers are being treated as strings, since ECMAScript uses "+" for both addition and string concatenation. You need to find some AS1 way to make sure the interpreter knows you are talking about numbers, not strings.
What happens if you put a .0 after all your numbers? e.g. 250.0?
Note: I just looked it up, and parseInt and parseFloat have been available since AS1.
parseInt
parseFloat

Related

Why do I keep getting an error that array indices must be positive?

It says the index in position 1 of the diff function must be a positive integer or a logical value which is it so why am I getting this error? I'm trying to implement the basic Euler method in MATLAB
y=zeros(1,6);
h=0;
x(1)= 0;
y(1)= 0;
i=1;
diff(y,x)= x+y
while h<=1
y(i+1)=y(i) + h*f(x(i))
h=h+0.2;
i=i+1;
end
Edit: Changed it to the code below but it still raises the same error in the line y(i+1)=...
y=zeros(1,6);
x=zeros(1,6);
h=0;
i=1;
g=x+y;
while h<=1
y(i+1)=y(i) + h*g(x(i),y(i));
h=h+0.2;
i=i+1;
end
Approach: I would recommend defining an anonymous function
diffh =#(x,y) x + y; % define this prior to use
to use later inside the loop.
Then changing one line
y(ii+1)=y(ii) + h*diffh(x(ii),y(ii));
should work. I've added the "h" to the end as a convention to remind me this is an anonymous function (see note at end).
% MATLAB R2019a
y = zeros(1,6);
x = zeros(1,6);
h=0;
ii=1;
diffh =#(x,y) x + y;
while h <= 1
y(ii+1)=y(ii) + h*diffh(x(ii),y(ii));
x(ii+1) = x(ii)+h;
h=h+0.2;
ii=ii+1;
end
Side note: I've also changed the index i to ii by convention (though MATLAB doesn't require this). Unless you overwrite their values, both i and j default as the sqrt(-1). You can absolutely use them as indices without issue (provided you don't later need complex or imaginary numbers). To ensure this never becomes an issue, many people just use ii and jj as a convention to preserve the default values.
Note that diff is a MATLAB function itself.
Using i as an index is mostly not a good idea in Matlab, because i is also imaginary number. Perhaps another name could solve the problem.

Reading TrueType 'cmap' Format 4 Subtable in Swift 3

How might one go about writing the following C code in Swift?
glyphIndex = *(&idRangeOffset[i] + idRangeOffset[i] / 2 + (c - startCode[i]))
I'm attempting to read a Format 4 TrueType character mapping table using a simple little binary data reader. All is well and good until pointer manipulation is involved, as I can barely make heads or tails of pointers when working in C, let alone ones masquerading around with Unsafe prefixes attached to them.
I've tried multiple things, but nothing seems to work quite right. I guess I'm just not exactly sure how to work with pointer "addresses" in Swift.
For example, here's a more complete idea of where I am:
// The following variables are all [UInt16]:
// - startCodes
// - endCodes
// - idDeltas
// - idRangeOffsets
var gids = [Int]()
// Iterate segments, skipping the last character code (0xFFFF)
for i in 0 ..< segCount - 1 {
let start = startCodes[i]
let end = endCodes[i]
let delta = idDeltas[i]
let rangeOffset = idRangeOffsets[i]
let charRange = start ..< (end + 1)
if rangeOffset == 0 {
gids.append(contentsOf: charRange.map { charCode in
return (charCode + delta) & 0xFFFF
})
}
else {
for charCode in charRange {
// ???
}
}
}
In the code above, you'll notice ???. This is where I retrieve the glyph index using the strange C-pointer-address-pointer-huh trick mentioned above. The problem is, I just can't figure it out. Replacing the variables I actually understand, here's what I've got:
for charCode in charRange {
Not too sure about this Actual value of idRangeOffset[i]
| |
v v
glyphIndex = *(&idRangeOffset[i] + rangeOffset / 2 + (charCode - start))
^
|
Or this
}
Are there any Swift 3 pointer gurus out there that can lead me on the path to enlightenment? Any help would be greatly appreciated!
If I translate your pseudo C code word by word into Swift, it would be something like this:
//"May not work" example, do no use this
glyphIndex = withUnsafePointer(to: &idRangeOffset[i]) {idRangeOffsetPointer in
//In some cases `idRangeOffsetPointer` can work as `&idRangeOffset[i]` in C...
(idRangeOffsetPointer + Int(rangeOffset) / 2 + Int(charCode - start)).pointee
//To make pointer operation in Swift, all integers need to be `Int`,
//And to match the C-rule of integer operation, you need to cast each portion to `Int` before adding operation
//The equivalent to C's dereferencing operator `*` in Swift is `pointee` property
}
But this may not work as expected because of the copy-in/copy-out semantics of Swift's inout parameter. Swift may create a temporal region which contains the single element idRangeOffset[i], and pass the address of it to idRangeOffsetPointer, so the result of the pointer operation may be pointing somewhere near the temporal region, which is completely useless.
If you want to get a meaningful result from the pointer operation, you may need to work in a context where all elements of the array are guaranteed to be placed in a contiguous region.
And also you should need to know that the C-statement:
glyphIndex = *(&idRangeOffset[i] + idRangeOffset[i] / 2 + (c - startCode[i]))
is based on the fact, that whole idRangeOffset and glyphIdArray are placed in a contiguous region without any gaps or paddings. (I assume you know well about Format 4.)
So, if your idRangeOffset contains only segCount elements, the following code would not work.
//"Should work" in a certain condition
glyphIndex = idRangeOffset.withUnsafeBufferPointer{idRangeOffsetBufferPointer in
let idRangeOffsetPointer = idRangeOffsetBufferPointer.baseAddress! + i
//`idRangeOffsetPointer` is equivalent to `&idRangeOffset[i]` in C inside this closure
return (idRangeOffsetPointer + Int(rangeOffset) / 2 + Int(charCode - start)).pointee
}
But with considering the pointer and array semantics in C, the code above is equivalent to this:
glyphIndex = idRangeOffset[i + Int(rangeOffset) / 2 + Int(charCode - start)]
//`*(&arr[i] + n)` is equivalent to `arr[i + n]` in C
I repeat, the Array idRangeOffset needs to contain whole content of idRangeOffset and glyphIdArray.
To add to what #OOPer said, I would suggest reading the whole cmap or subtables of interest into memory and working with them in Swift using documentation as a guide; see, for example, https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html. You could also use a C implementation as a reference, but that is not a good path unless you are an experienced C programmer: there are too many subtleties in C that can and will bite you. In C it's really convenient to work with a cmap in terms of pointers and offsets. Because Swift is not that pointer-friendly, it's better to just use offsets into a table. You will likely run into problems interpreting different parts of the map as values of different types, but at least you won't have to deal with pointer magic.

how to check in matlab if a 3D array has at least one non zero element?

I tried to check if a 3D array is not all zeros using the next code:
notAll_n0_GreaterThan_ni=1;
while notAll_n0_GreaterThan_ni
notAll_n0_GreaterThan_ni=0;
mask=(n0<ni);
numDimensions=ndims(mask);
for dim_ind=1:numDimensions
if any(mask,dim_ind)
notAll_n0_GreaterThan_ni=1;
break;
end
end
if notAll_n0_GreaterThan_ni
n0(mask)=n0(mask)+1;
end
end
It seems I have error in the code because at the end I get for example: n_0(11,3,69)=21 while ni(11,3,69)=21.1556.
I can't find the error. I'll appreciate if someone shows me where I'm wrong and also if there is a simpler way to check existence of nonzero elements in a 3D array.
Let x denote an n-dimensional array. To check if it contains at least one non-zero element, just use
any(x(:))
For example:
>> x = zeros(2,3,4);
>> any(x(:))
ans =
0
>> x(1,2,2) = 5;
>> any(x(:))
ans =
1
Other, more exotic possibilities include:
sum(abs(x(:)))>0
and
nnz(x)>0
This is what you looking for
B = any(your_Array_name_here(:) ==0); no need for loops
the (:) turns the elements of your_Array into a single column vector, so you can use this type of statement on an array of any size
I 've tested this and it works
A = rand(3,7,5) * 5;
B = any(A(:) ==0);

Indexing sliced array in matlab??? [duplicate]

For example, if I want to read the middle value from magic(5), I can do so like this:
M = magic(5);
value = M(3,3);
to get value == 13. I'd like to be able to do something like one of these:
value = magic(5)(3,3);
value = (magic(5))(3,3);
to dispense with the intermediate variable. However, MATLAB complains about Unbalanced or unexpected parenthesis or bracket on the first parenthesis before the 3.
Is it possible to read values from an array/matrix without first assigning it to a variable?
It actually is possible to do what you want, but you have to use the functional form of the indexing operator. When you perform an indexing operation using (), you are actually making a call to the subsref function. So, even though you can't do this:
value = magic(5)(3, 3);
You can do this:
value = subsref(magic(5), struct('type', '()', 'subs', {{3, 3}}));
Ugly, but possible. ;)
In general, you just have to change the indexing step to a function call so you don't have two sets of parentheses immediately following one another. Another way to do this would be to define your own anonymous function to do the subscripted indexing. For example:
subindex = #(A, r, c) A(r, c); % An anonymous function for 2-D indexing
value = subindex(magic(5), 3, 3); % Use the function to index the matrix
However, when all is said and done the temporary local variable solution is much more readable, and definitely what I would suggest.
There was just good blog post on Loren on the Art of Matlab a couple days ago with a couple gems that might help. In particular, using helper functions like:
paren = #(x, varargin) x(varargin{:});
curly = #(x, varargin) x{varargin{:}};
where paren() can be used like
paren(magic(5), 3, 3);
would return
ans = 16
I would also surmise that this will be faster than gnovice's answer, but I haven't checked (Use the profiler!!!). That being said, you also have to include these function definitions somewhere. I personally have made them independent functions in my path, because they are super useful.
These functions and others are now available in the Functional Programming Constructs add-on which is available through the MATLAB Add-On Explorer or on the File Exchange.
How do you feel about using undocumented features:
>> builtin('_paren', magic(5), 3, 3) %# M(3,3)
ans =
13
or for cell arrays:
>> builtin('_brace', num2cell(magic(5)), 3, 3) %# C{3,3}
ans =
13
Just like magic :)
UPDATE:
Bad news, the above hack doesn't work anymore in R2015b! That's fine, it was undocumented functionality and we cannot rely on it as a supported feature :)
For those wondering where to find this type of thing, look in the folder fullfile(matlabroot,'bin','registry'). There's a bunch of XML files there that list all kinds of goodies. Be warned that calling some of these functions directly can easily crash your MATLAB session.
At least in MATLAB 2013a you can use getfield like:
a=rand(5);
getfield(a,{1,2}) % etc
to get the element at (1,2)
unfortunately syntax like magic(5)(3,3) is not supported by matlab. you need to use temporary intermediate variables. you can free up the memory after use, e.g.
tmp = magic(3);
myVar = tmp(3,3);
clear tmp
Note that if you compare running times with the standard way (asign the result and then access entries), they are exactly the same.
subs=#(M,i,j) M(i,j);
>> for nit=1:10;tic;subs(magic(100),1:10,1:10);tlap(nit)=toc;end;mean(tlap)
ans =
0.0103
>> for nit=1:10,tic;M=magic(100); M(1:10,1:10);tlap(nit)=toc;end;mean(tlap)
ans =
0.0101
To my opinion, the bottom line is : MATLAB does not have pointers, you have to live with it.
It could be more simple if you make a new function:
function [ element ] = getElem( matrix, index1, index2 )
element = matrix(index1, index2);
end
and then use it:
value = getElem(magic(5), 3, 3);
Your initial notation is the most concise way to do this:
M = magic(5); %create
value = M(3,3); % extract useful data
clear M; %free memory
If you are doing this in a loop you can just reassign M every time and ignore the clear statement as well.
To complement Amro's answer, you can use feval instead of builtin. There is no difference, really, unless you try to overload the operator function:
BUILTIN(...) is the same as FEVAL(...) except that it will call the
original built-in version of the function even if an overloaded one
exists (for this to work, you must never overload
BUILTIN).
>> feval('_paren', magic(5), 3, 3) % M(3,3)
ans =
13
>> feval('_brace', num2cell(magic(5)), 3, 3) % C{3,3}
ans =
13
What's interesting is that feval seems to be just a tiny bit quicker than builtin (by ~3.5%), at least in Matlab 2013b, which is weird given that feval needs to check if the function is overloaded, unlike builtin:
>> tic; for i=1:1e6, feval('_paren', magic(5), 3, 3); end; toc;
Elapsed time is 49.904117 seconds.
>> tic; for i=1:1e6, builtin('_paren', magic(5), 3, 3); end; toc;
Elapsed time is 51.485339 seconds.

MATLAB R2012b - Passing arrays and ints into evalin(symengine,expression)

I'm attempting to generate the Laguerre polynomials, and then evaluate them elementwise over a coordinate array.
Presently my code looks something like:
[X,Y] = meshgrid(x_min:mesh_size:x_max,y_min:mesh_size:y_max);
const_p=0;
const_l=1; %At present these two values don't really matter, any integer will do
coord_r = sqrt(X.^2 + Y.^2)
lag_input = num2str(coord_r.^2)
u_pl = evalin(symengine,['orthpoly::laguerre(',num2str(const_p),',',num2str(const_l),',',lag_input,')']);
However, that returns the following error for the last line;
Error using horzcat
Dimensions of matrices being concatenated are not consistent.
I assumed that this was because the three objects being converted to strings had different sizes, but after making them the same size the problem persists.
I'd rather avoid looping through each element if I can avoid it.
I would go about this slightly differently. How about the below? Note that I changed const_p and const_l from your choices because the resulting Laguerre Polynomial is spectacularly dull otherwise.
const_p = 2;
const_l = 1;
%generate the symbolic polynomial in x
lagpoly=feval(symengine,'orthpoly::laguerre',const_p,const_l,'x');
%Find the polynomical coefficients so we can evaluate using MATLAB's poly
coeff=double(feval(symengine,'coeff',lagpoly));
%generate a matrix the same size as coord_r in the original question
x=rand(512);
%Do the evaluation
u_pl=polyval(coeff,x);
#WalkingRandomly has the best way to do this if you need fast numeric results, which is usually the case. However, if you need exact analytical values, there is a trick that at you can use to avoid a for loop: MuPAD's map function. This is how almost all MuPAD functions must be vectorized as they're usually designed for scalar symbolic variables rather than arrays of numeric values. Here's a basic example:
const_p = 2;
const_l = 1;
mesh_size = 0.2;
x_min = 0;
x_max = 1;
y_min = 0;
y_max = 1;
[X,Y] = meshgrid(x_min:mesh_size:x_max,y_min:mesh_size:y_max);
coord_r = sqrt(X.^2 + Y.^2);
lagpoly = evalin(symengine,['map(' char(sym(coord_r)) ...
',x->orthpoly::laguerre(' char(sym(const_p)) ...
',' char(sym(const_l)) ',x))'])
which returns
lagpoly =
[ 3, 121/50, 47/25, 69/50, 23/25, 1/2]
[ 121/50, 76/25 - (3*2^(1/2))/5, 31/10 - (3*5^(1/2))/5, 16/5 - (3*2^(1/2)*5^(1/2))/5, 167/50 - (3*17^(1/2))/5, 88/25 - (3*26^(1/2))/5]
[ 47/25, 31/10 - (3*5^(1/2))/5, 79/25 - (6*2^(1/2))/5, 163/50 - (3*13^(1/2))/5, 17/5 - (6*5^(1/2))/5, 179/50 - (3*29^(1/2))/5]
[ 69/50, 16/5 - (3*2^(1/2)*5^(1/2))/5, 163/50 - (3*13^(1/2))/5, 84/25 - (9*2^(1/2))/5, 1/2, 92/25 - (3*34^(1/2))/5]
[ 23/25, 167/50 - (3*17^(1/2))/5, 17/5 - (6*5^(1/2))/5, 1/2, 91/25 - (12*2^(1/2))/5, 191/50 - (3*41^(1/2))/5]
[ 1/2, 88/25 - (3*26^(1/2))/5, 179/50 - (3*29^(1/2))/5, 92/25 - (3*34^(1/2))/5, 191/50 - (3*41^(1/2))/5, 4 - 3*2^(1/2)]
Calling double(lagpoly) will convert the result to floating point and you'll see that this is the same as the solution provided by ##WalkingRandomly (given the same inputs). Of course you could probably use the symbolic polynomial or its coefficients to find the same thing manually, though it's unfortunate that polyval isn't overloaded for class sym (there's evalp but it's also not vectorized so it would need to be used in conjunction with map).

Resources