getting column of array in C99? - arrays

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.

Related

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}})))

Pascal - What is the most efficient way to pass an array as a parameter?

This is mostly for dynamic arrays though.
I have known of three ways to pass an array as a parameter by far:
As a value parameter: this results in the entire array being copied and is considered inefficient by many books (except for this, which creates confusion among me).
As a VAR parameter: this results in only the address of the first element being copied, and is considered optimal by many books, with the drawback of possibility of accidentally changing the array content when you don't need to do so.
As a pointer: this is something I don't usually see. What is the difference between this and the second method? As for another (possibly) relevant stuff, the wiki says that the dynamic array is itself a pointer with automatic dereferencing, so when passing one to a function, shouldn't it be passed as a pointer anyway?
So which method should be used generally?

Expression in arrays to get a scalar one. Matlab

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?

Multi dimensional array with varying size

I want to make a 2D array "data" with the following dimensions: data(T,N)
T is a constant and N I dont know anything about to begin with. Is it possible to do something like this in fortran
do i = 1, T
check a few flags
if (all flags ok)
c = c+ 1
data(i,c) = some value
end if
end do
Basically I have no idea about the second dimension. Depending on some flags, if those flags are fine, I want to keep adding more elements to the array.
How can I do this?
There are several possible solutions. You could make data an allocatable array and guess the maximum value for N. As long as you don't excess N, you keep adding data items. If a new item would exceed the array size, you create a temporary array, copy data to the temporary array, deallocate data and reallocate with a larger dimension.
Another design choice would be to use a linked list. This is more flexible in that the length is indefinite. You loss "random access" in that the list is chained rather than indexed. You create an user defined type that contains various data, e.g., scalers, arrays, whatever, and also a pointer. When you add a list item, the pointer points to that next item. The is possible in Fortran >=90 since pointers are supported.
I suggest searching the web or reading a book about these data structures.
Assuming what you wrote is more-or-less how your code really goes, then you assuredly do know one thing: N cannot be greater than T. You would not have to change your do-loop, but you will definitely need to initialize data before the loop.

How to increase array size on-the-fly in Fortran?

My program is running though 3D array, labelling 'clusters' that it finds and then doing some checks to see if any neighbouring clusters have a label higher than the current cluster. There's a second array that holds the 'proper' cluster label. If it finds that the nth adjoining cluster is labelled correctly, that element is assigned to 0, otherwise is assigns it to the correct label (for instance if the nth site has label 2, and a neighbour is labeled 3, the 3rd element of the labelArray is set to 2). I've got a good reason to do this, honest!
All I want is to be able to assign the nth element of the labelArray on the fly. I've looked at allocatable arrays and declaring things as labelArray(*) but I don't really understand these, despite searching the web, and StackOverflow.
So any help on doing this would be awesome.
Here is a Stack Overflow question with some code examples showing several ways of using Fortran allocatable arrays: How to get priorly-unkown array as the output of a function in Fortran: declaring, allocating, testing for being already being allocated, using the new move_alloc and allocation on assignment. Not shown there is explicit deallocation, since the examples are using move_alloc and automatic deallocation on exit of a procedure.
P.S. If you want to repeatedly add one element you should think about your data structure approach. Adding one element at a time by growing an array is not an efficient approach. To grow an array from N elements to N+1 in Fortran will likely mean creating a new array and copying all of the existing elements. A more appropriate data structure might be a linked list. You can create a linked list in Fortran by creating a user-defined type and using pointers. You chain the members together, pointing from one to the next. The overhead to adding another member is minor. The drawback is that it is easiest to access the members of the list in order. You don't have the easy ability of an array, using indices, to access the members in any order.
Info about linked lists in Fortran that I found on the web: http://www-uxsup.csx.cam.ac.uk/courses/Fortran/paper_12.pdf and http://www.iag.uni-stuttgart.de/IAG/institut/abteilungen/numerik/images/4/4c/Pointer_Introduction.pdf
If you declare an array allocatable, you use deffered shape in the form real,
allocatable :: labelArray(:,:)
, or
real,dimension(:,:),allocatable :: labelArray
with number of double colons meaning rank (number of your indexes) of your array.
If the array is unallocated you use
allocate(labelarray(shapeyouwant))
with the correct number of indexes. For example allocate(labelarray(2:3,-1:5)) for array with indexes 2 to 3 in demension 1 and -1 to 5 in dimension 2.
For change of dimension you have to deallocate the array first using
deallocate(labelArray)
To reallocate an allocated array to a new shape you first need to allocate a new array with the new shape, copy the existing array to the new array and move the reference of the old array to the new array using move_alloc().
call allocate(tmp(size_old+n_enlarge))
tmp(1:size_old) = array(1:size_old)
call move_alloc(tmp, array)
The old array is deallocated automatically when the new array reference is moved by move_alloc().
Fortran 95 deallocates arrays automatically, if they fall out of scope (end of their subroutine for example).
Fortran 2008 has a nice feature of automatic allocation on assignment. If you say array1=array2 and array1 is not allocated, it is automatically allocated to have the correct shape.
It can also be used for re-allocation (see also Fortran array automatically growing when adding a value and How to add new element to dynamical array in Fortran 90)
labelArray = [labelArray, new_element]
Late comment... check Numerical Recipes for Fortran 90. They implemented a nice reallocate function that was Fortran 90 compliant. Your arrays must be pointer attributed in this case, not allocatable attributed.
The function receives the old array and desired size, and returns a pointer to the new resized array.
If at all possible, use Fortran 95 or 2003. If 2003 is impossible, then 95 is a good compromise. It provides better pointer syntax.

Resources