Expression in arrays to get a scalar one. Matlab - arrays

I have a vector array that contains Time values in an asceding order. With relational expressions I can obtain subset values from that array, after that I need the first value of that subset without creating new variables.
For example.
Time is an column vector, then I can use Time(something==X) to get a subset values of Time, but then I need the first value of Time(something==X), I can't use Time(something==X)(1) like some programming languages u.u

Unfortunately with MATLAB you need to use temporary variables. It doesn't support this kind of indexing, though it is quite natural and I would love if they supported it.
You would have to do this:
x = Time(something==X);
y = x(1);
Octave does have the ability of doing this kind of indexing though. The only way I can think of you escaping this is if you use cell arrays. However, if you want to use a normal vector, then you're SOL.
EDIT: May 13th, 2014 - Referencing David's comment, it is possible to do this without a temporary variable, but readability is very poor. In the end, a temporary variable is still the better way for readability and reproducibility. Check the following SO post that he has referenced:
How can I index a MATLAB array returned by a function without first assigning it to a local variable?

Related

getting column of array in C99?

In C if I have:
int grades[100][200];
and want to pass the first row, then I write: grades[0], but what if I want to pass first column? writing this won't help grades[][0]
You can't pass columns in C. You pass pointers to the beginning of some continuous data.
Rows in C are written continuously in memory, so you pass the pointer to the first element of some row (you do it implicitly by using its name: matrix[row]; an explicit version would be &matrix[row][0]), and you can use the row by iterating over the continuous memory.
To use columns, you need to pass the whole array (a pointer to the first element in the 2D array, actually), and pass also the length of the rows, and then the function has to jump that length to jump from an element of the same column to the next one. This is one of many possible solutions, you could develop any other solution, for example copying the column in a temporary array as some comment pointed out; but this one is commonly used in cblas functions for example.
If it helps to visualize, a 2-dimensional array is an array of arrays, it's not formulated as a matrix. Thereby, we can pass a sub-array (i.e., a row), but there's no direct way of passing a column.
One way to achieve this is to loop over the outer array, pick the element at the fixed location (mimicking the "column"), and use the values to create a separate array, or pass to function that needs to process the data.
Matrixes do not exist in C (check by reading the C11 standard n1570). Only arrays, and in your example, it is an array of arrays of int. So columns don't exist neither.
A good approach is to view a matrix like some abstract data type (using flexible array members ....) See this answer for details.
Consider also using (and perhaps looking inside its source code) the GNU scientific library GSL, and other libraries like OpenCV, see the list here.
In some cases, arbitrary precision arithmetic (with gmplib) could be needed.

Matlab access array element in one line

a = 0:99
s = size(a)
disp(s(2))
Can the last two lines be written as one? In other languages I am able to do f(x)[i], but Matlab seems to complain.
In this specific case where you are using the size function, you can add an additional argument to specify the dimension you want the size of, allowing you to easily do this in one line:
disp(size(a, 2)); % Displays the size of the second dimension
In the more general case of accessing an array element without having to store it in a local variable first, things get a little more complicated, since MATLAB doesn't have the same kind of indexing shorthand you would find in other languages. Octave, for example, would allow you to do disp(size(a)(2)).
It is possible to collapse those two lines in one single statement and achieve a sort of f(x)[i] thanks to the functional form of the indexing operator: subsref.
disp(subsref(size(a), struct('type', '()', 'subs', {{2}})))

Most efficient way to add a constant to a column of an array in LabVIEW?

I want to add a constant to the second column of an array.
I do this as shown below:
Where for illustration the values are as follows:
What is the most efficient way of adding a constant to an array column?
With a question about efficiency you should supply number. For anything lower than a 1000 x 1000 2D array I can't measure the difference. Usually it is best to simply test it.
Here the code for testing (same answer as crossrulz)
With a 10000 x 10000 array option 2 becomes about 10 times faster.
One comment unless you are in a very high demanding situation, readability is usually preferred over efficiency. In my opinion option 2 is more readable since it has no for loop and the constant is presented as a constant instead of an array.
But you can get more efficient than that by using the In Place Element structure. The image below shows two different ways to add 5 to a column. The second one avoids making a memory copy of the entire array. Indexing out a column of an array with Index Array and then modifying it requires a shift of underlying memory format, even though the array is going to be put back in the Replace Array Subset. The In Place Element structure gives enough context to LabVIEW for it to recognize that the Add can be done without data copies.
Index Array to get the second column, add your constant, and then Replace Array Subset to replace the second column.

What are the advantages and disadvantages of 3d array in Mathematica

Edited...
Thanks for every one to try to help me!!!
i am trying to make a Finite Element Analysis in Mathemetica.... We can obtain all the local stiffness matrices that has 8x8 dimensions. I mean there are 2000 matrices they are similar but not same. every local stiffness matrix shown like a function that name is KK. For example KK[1] is first element local stiffness matrix
i am trying to assemble all the local matrices to make global stiffness matrix. To make it easy:
Do[K[e][i][j]=KK[[e]][[i]][[j]],{e,2000},{i,8},{j,8}]....edited
Here is my question.... this equality can affect the analysis time...If yes what can i do to improve this...
in matlab this is named as 3d array but i don't know what is called in Mathematica
what are the advantages and disadvantages of this explanation type in Mathematica...is t faster or is it easy way
Thanks for your help...
It is difficult to understand what your question is, so you might want to reformulate it.
As others have mentioned, there is no advantage to be expected from a switch from a 3D array to DownValues or SubValues. In fact you will then move from accessing data-structures to pattern matching, which is powerful and the real strength of Mathematica but not very efficient for what you plan to do, so I would strongly suggest to stay in the realm of ordinary arrays.
There is another thing that might not be clear for someone more familiar with matlab than with Mathematica: In Mathematica the "default" for arrays behave a lot like cell arrays in matlab: each entry can contain arbitrary content and they don't need to be rectangular (as High Performance Mark has mentioned they are just expressions with a head List and can roughly be compared to matlab cell arrays). But if such a nested list is a rectangular array and every element of it is of the same type such arrays can be converted to so called PackedArrays. PackedArrays are much more memory efficient and will also speed up many calculations, they behave in many respect like regular ("not-cell") arrays in matlab. This conversion is often done implicitly from functions like Table, which will oten return a packed array automatically. But if you are interested in efficiency it is a good idea to check with Developer`PackedArrayQ and convert explicitly with Developer`ToPackedArray if necessary. If you are working with PackedArrays speed and memory efficiency of many operations are much better and usually comparable to verctorized operations on normal matlab arrays. Unfortunately it can happen that packed arrays get "unpacked" by some operations, so if calculations become slow it is usually a good idea to check if that has happend.
Neither "normal" arrays nor PackedArrays are restricted in the rank (called Depth in Mathematica) they can have, so you can of course create and use "3D arrays" just as you can in matlab. I have never experienced or would know of any efficiency penalties when doing so.
It probably is of interest that newer versions of Mathematica (>= 10) bring the finite element method as one of the solver methods for NDSolve, so if you are not doing this as an exercise you might want to have a look what is available already, there is quite excessive documentation about it.
A final remark is that you can instead of kk[[e]][[i]][[j]] use the much more readable form kk[[e,i,j]] which is also easier and less error prone to type...
extended comment i guess, but
KK[e][[i]][[j]]
is not the (e,i,j) element of a "3d array". Note the single
brackets on the e. When you use the single brackets you are not denoting an array or list element but a DownValue, which is quite different from a list element.
If you do for example,
f[1]=0
f[2]=2
...
the resulting f appears similar to an array, but is actually more akin to an overloaded function in some other language. It is convenient because the indices need not be contiguous or even integers, but there is a significant performance drawback if you ever want to operate on the structure as a list.
Your 'do' loop example would almost certainly be better written as:
kk = Table[ k[e][i][j] ,{e,2000},{i,8},{j,8} ]
( Your loop wont even work as-is unless you previously "initialized" each of the kk[e] as an 8x8 array. )
Note now the list elements are all double bracketed, ie kk[[e]][[i]][[j]] or kk[[e,i,j]]

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