No BSD License  

Highlights from
flat

3.33333

3.3 | 10 ratings Rate this file 4 Downloads (last 30 days) File Size: 199 Bytes File ID: #17257

flat

by Vincent

 

31 Oct 2007 (Updated 31 Oct 2007)

flatten a matrix, i.e. make it a vector

| Watch this File

File Information
Description

Warning: this is obviously a pretty dumb function, that will be useful when you need to often vectorize indexed matrices.

In matlab you usually vectorize a multidimensional matrix by indexing it with (:), e.g. x(:).

However, if you are trying to vectorize only selected columns or lines in the matrix this is not possible, meaning you can't do something like

    hist (x(index,:))
    sum (x(index,:))

The usual workaround implies copying the needed elements as a new matrix, as in

   x2 = x(index,:);
   hist (x2(:));
   sum (x2(:));

which crowds your namespace with useless variables and makes your code more complex. Using the (allegedly dumb, but convenient) flat() function, this becomes

   hist(flat(x(index,:)));
   sum(flat(x(index,:)));

which is both easy to understand, clean and doesn't store the intermediate values.

This was inspired by the numpy x.flat() function.

MATLAB release MATLAB 7.3 (R2006b)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (17)
31 Oct 2007 Yi Cao

I do not see any necessity for this function. We have many ways to get flatted sub-matrix. One obvious way is to use reshape command:

hist(reshape(x(index,:),[],1));

For sum function, we can simply use

sum(sum(x(index,:)));

01 Nov 2007 Mathias Ortner

I just put a comment since I find the previous one unfair. I have my own functions that actually are colshape and lineshape for flattening arrays.

I don not see the utility of tagging files as 'not usefull'

02 Nov 2007 Duane Hanselman

I posted an non-starred review of this file yesterday that was somehow removed. (How does that happen?) Even today, I cannot find where this is useful. Here is the entire content of the file:
function x=flat(x)
% x = flat(x) flatten a matrix.
% useful when you can't append "(:)" to an expression
% e.g. flat(x(index,:))
% dumb but convenient
% Vincent Noel 2007
x = x(:);
return %Note that this line is NOT needed!

Since this is a one-liner, why not just create an anonymous function when you need it, e.g., flat = @(x) x=x(:);

02 Nov 2007 Dimitri Shvorob

Redundant, as shown below :(

04 Nov 2007 Mathias Ortner

The more time I spend on this file exchange, the more I feel like some people truly believe they are sort of "matlab gurus" - and nobody can tel why they beleive so. I dont see the point in being aggressive when reviewing a file. Say "well coded" or "badly done" but why "not useful" ?? This is meaningless.

I also beleive that there are some utility for this kind of function. For instance :
sum(flat(det(A))).

04 Nov 2007 Mathias Ortner

Sorry my example is bad.

sum(flat(A^2)) is better.

Still - I dont understand. The author says its dumb, and some people keep on saying "useless" - "useless".

People ! Beware !! Don't post your files anymore, some terrorizing gurus are reigning over here !!

06 Nov 2007 V P

Vincent says
"you can't do something like hist (x(index,:))"

Sure I never tried to do this, but Matlab does it easily, building a histogram for every column. In addition, if index is a scalar, you get a histogram for selected row.

Concerning term "flattening". In many physical applications this is a synonym for removal a low-frequency component.

About "vectorizing". Within ML community this is a coding style based on matrix operations, i.e. avoiding any loops.

Vincent means making a vector from a matrix. According to ML conventions, elements of any matrix can be addressed as elements of a vector, so that there is an intrinsiv dualism matrix/vector, i.e. no need in any additional "vectorizing". If there are some reasons in building some nonstandard vectors, that could be interesting. If a matrix is not very small, one can build very many vectors out of it. For instance, out of M by N matrix one can build factorial(M*N) different vectors M*N long. Which of these possibilities could be of interest? Row-wise ordering (trivial)? Diagonal ordering? Concentric or spiral ordering (clock/counterclock, different starts)? Random ordering(tassing)? What is new and helpful for a Matlab user?

07 Nov 2007 John D'Errico

I've kept out of this for a while. I won't call it "not useful", but the fact remains this is trivial as a tool. Mathias says the code is necessary for a problem like sum(flat(A^2)), but this is easily done directly with no recourse to a new tool.

sum(reshape(A^2,1,[]))

In fact, the reshape trick will work for any circumstance that Mathias cares to mention. (Unless your Matlab release is really old, maybe version 4?) Or do as Duane has suggested, and create an anonymous function. @(x) x(:).

The only use I can think of for this function is for someone who does not know Matlab as a language, and has no real interest in learning Matlab either.

As for the code itself, it lacks an H1 kine, so the lookfor utility fails to work on it. The help itself is reasonably explanatory. There is no error checking, were I to write such a code, I'd probably have a check on the total number of arguments. (I'll admit that error checks on this code seem silly to implement at all.)

There is really only one functional line of code in this - a trivial one. Then the author puts a return statement, which is funny in a way, since a return is not necessary to have at the end of a function. Perhaps the author has spent too much time writing in other languages? Python perhaps?

As for a rating, I could not justify calling it "excellent". This is truly a trivial code, with a couple of things I found to complain about in such a short code. And how could I even call it "good"? At the other end of the spectrum, 2 ("needs improvement") seems not to be appropriate either. Were you to make this code perfect in every other way, its still too trivial to bother with.

So, I'm left with either a rating of 3 ("fair"), which is what I might use to describe an otherwise useful code with a few flaws, or a 1 ("poor"). This is an utterly TRIVIAL code after all, with simple alternatives. As I said, the only reason for this code is if you don't know or care how to program in Matlab. My guess is this is why several reviewers have given it such poor reviews - it is an insult to them.

In the end, I'll end with a rating of 2 as the numerical rating I'd choose, even though "Needs improvement" is not really appropriate.

07 Nov 2007 Vincent Noel

Hey all,
(I've already tried to reply but the system apparently ate my comment. bah)

thanks for all the comments. My reason for writing this function is indeed poor: I spend a lot of time in my code computing distributions of indexed matrices, such as in [n,x]=hist(blabla(:,index1,index2,:)). By default, matlab returns a distribution for each indexed column/row, as do sum(), mean(), std(), etc. This is not what I want, I want a single distribution for all data points. I know I can use reshape or tricks such as sum(sum()), but I didn't like them because 1) you need to track and take into account the number of dimensions of the matrix, which can change, and/or 2) these tricks IMHO make the code a little bit harder to write and parse, as they hide the simplicity of the procedure behind ()'s and []'s and extra arguments. I'm the first to admit it is a "comfort" function.

For the record, I've used matlab for years, recently tried python, and liked the way the flat() function made the code look cleaner and more straightforward to write and read. You could say I wrote it for stylistic purposes :-) Note that I've never implied that this function did anything mind-blowing, and the guidelines for submitting an m-file don't mention that it needs to be useful.

I'm sorry to see that many smart people have wasted their time commenting here, I didn't expect this... I can remove this submission if needed.

07 Nov 2007 V P

Vincent wrote
"I'm sorry to see that many smart people have wasted their time commenting here, I didn't expect this... "

You are probably the smartest one here.
Now you have clearly specified that you are interested in ALL elements of an array, without any additional ordering. In this case, why do you ignore Duane's remark about colon?

Otherwise, good luck.

18 Nov 2007 Shaun Deanelman

That's somewhat amazing that the guy who wrote RENVAR (which I find useful in spite of its very simplicity) cannot find where FLAT is useful. Let's remind that RENVAR X Y simply does: Y = X; CLEAR X. FLAT could actually save a few lines of code: A = rand(3,3,3); B = A(:,2,:); MEAN(B(:)), CLEAR B. With FLAT: MEAN(FLAT(A(:,2,:))) is enough. Finally, FLAT may save 2 lines of code whereas RENVAR saves only 1 line! So please, RENVAR's author, be consistent with yourself! You should be the one knows that simple does not mean useless. A rating of 5 should compensate for the close-minded ratings.

20 Nov 2007 V P

A = rand(3,3,3);

Shaun suggests to compare
 B = A(:,2,:); MEAN(B(:)), CLEAR B.

With: MEAN(FLAT(A(:,2,:)))

Point 2. CLEAR B does not improve anything. It is not necessary and decreases speed.
At the same time the computer calculates
MEAN(FLAT(A(:,2,:))) exactly like
B=flat(A(:,2,:)). MEAN (B).

In order to prove any profit of flat, one hase to compare two versions:

1) tic,B=flat(A(:,2,:)). C=MEAN (B), t=toc

and

2)tic, B = A(:,2,:); C=MEAN(B(:)), t=toc

I should be impressed if the first version will work notably faster. I expect the opposite.

21 Jun 2008 Gregory Walsh  
24 Jun 2008 Jos x@y.z

This submission (still) lacks a proper help section (H1 line, example, See Also line). Therefore, I doubt this will be useful to anyone who does not has any experience in matlab syntax.

Moreover, flat(x) equals reshape(x,1,[]) in all respects, but in the latter it is immediately clear (possibly after typing "help reshape") that you will end up with a row vector. "help flat" tells you nothing useful ...

My rating of 2 stars reflects the needed improvement of the help section.

14 Apr 2009 Daniel Armyr

This is a function that I have been lacking for a while. The real fix would be to allow sum() std() etc to accept a vector as the dimension argument, but untill Mathworks fixes that, this will give cleaner code.

But yeah, get that help line fixed.

04 Nov 2009 Daniel Armyr

After having had this file in my librarby now for a moth, I am upping the rating to a five. The help section is still kinda child-like, but the fact is that there is no file-exchange sumbission I have used more than this little piece of code.

It may be trivial, and self-named gurus might find it beneath them to use it, but for those of us who code matlab for a living and need to type legible code accurately and fast, it is a perfect tool.

In particular:
a = rand(3,4,5,6);
b = mean(flat(a(:,1,:,2));

Is as legible and as hard to get wrong as they come.

15 Jul 2010 Ben

Love it.

Please login to add a comment or rating.
Updates
31 Oct 2007

insert a warning in the description

Tag Activity for this File
Tag Applied By Date/Time
matrices Vincent 22 Oct 2008 09:33:23
flat matrix Vincent 22 Oct 2008 09:33:23
flatten Vincent 22 Oct 2008 09:33:23
vectorize Vincent 22 Oct 2008 09:33:23
indexed matrices Vincent 22 Oct 2008 09:33:23
matrix manipulation Vincent 22 Oct 2008 09:33:23

Contact us at files@mathworks.com