Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 22006

How to extract a row of a matrix

In every other language if I have a matrix, if I call a mono-dimensional index, the result will be an array.I don't know why in Matlab if you take a single index of a matrix, you'll get a single element, that's stupid.
Anyway in C:

mat[4][4];

mat[0] is an array.

In Matlab:

mat=[1 2; 3 4];

How do I take the first row of the matrix? mat(1) is 1, not [1 2].

EDIT: There is another problem, I have a problem with this function:

function str= split(string, del)

index=1;
found=0;

str=['' ; ''];

for i=1:length(string)
    if string(i)==del
        found=1;
        index=1;
    elseif found==1
        str(2,index)=string(i);
        index=index+1;
    else
        str(1,index)=string(i);
        index=index+1;
    end
end

end

This returns sometimes a matrix and sometimes an array.
For example if I use split('FF','.') I get 'FF' as result, but what if I want to return a matrix? I can't even choose the dimensione of the matrix, in this context a weak typed language is a big disvantage.

Upvotes: 1

Views: 3422

Answers (3)

topchef
topchef

Reputation: 19823

From Matrix Indexing in MATLAB:

When you index into the matrix A using only one subscript, MATLAB treats A as if its elements were strung out in a long column vector, by going down the columns consecutively

I just hope it doesn't look stupid to you anymore (along with the right answers from angainor and Marwan)

Upvotes: 2

Max Doumit
Max Doumit

Reputation: 1115

This will extract the second row

vector = mat(2,:)

And This will extract the second column

vector = mat(:,2) 

You can use

vector = mat(end,:)

To extract the last row

Hope this helps you

Upvotes: 5

angainor
angainor

Reputation: 11810

You have to say which columns you want. : stands for all indices in a dimension, so to take first row

mat(1,:)

It is not stupid, but useful. If you address a matrix with only one index, it implicitly gets converted to a vector. This gives you the option to use linear indices (see sub2ind).

Upvotes: 9

Related Questions