How can i loop a matrix without knowing is size?

Hello!
So, i'm trying to make a loop where i have a matrix to go through and save their elements in a vector. Just note that i don't know the size of the matrix. So how can i do it?
Thanks!

2 件のコメント

Star Strider
Star Strider 2019 年 3 月 1 日
Are you somehow prevented from using the size function?
Joana Santos
Joana Santos 2019 年 3 月 1 日
No, i just didn't know how to use :D

サインインしてコメントする。

 採用された回答

Bob Thompson
Bob Thompson 2019 年 3 月 1 日

0 投票

So, you have two matrices, one outside the loop, and one inside? Which one are you not sure about the size of?
If it is the outside loop you can set the loop bounds to be dependent on the size of the matrix.
for i = 1:size(mat,1) % (mat,1) for rows, (mat,2) for columns and so on

6 件のコメント

Joana Santos
Joana Santos 2019 年 3 月 1 日
Yes, that's it!
So it will be something like this... ?
mat = [ 1 2 3 ; 4 5 6]
v = zeros(1,6)
for i = 1: size(mat,1)
v(i) = mat(i)
end
P.S: i want this: v = [1 2 3 4 5 6]
Joana Santos
Joana Santos 2019 年 3 月 1 日
(In this case i know the size of the matrix but it's just an example)
Bob Thompson
Bob Thompson 2019 年 3 月 1 日
編集済み: Bob Thompson 2019 年 3 月 1 日
Not quite. Using size in this manner will only loop through one dimension. Because you have two dimensions in 'mat' then you would actually need to do two loops, one for each direction.
However, because you are just trying to reorganize your data into a single dimension you can actually just use the reshape function.
v = reshape(mat,[n,1]);
Joana Santos
Joana Santos 2019 年 3 月 1 日
This is just an example. I pretend to use this code in a more complex function, but i need some bases...
I made this, but i still don't get the result. Where am i wrong?
mat = [ 1 2 3 ; 4 5 6]
v = zeros(1,6)
for i = 1: size(mat,1)
for j = 1:size(mat,1)
v(i) = mat(i,j)
end
end
Bob Thompson
Bob Thompson 2019 年 3 月 1 日
It's your indexing for v. Your i loop only goes from 1:2, so indexing v with (i) will just give you v(1) or v(2). You need to change this to be a combination of i and j.
v((i-1)*size(mat,2)+j) = mat(i,j);
Also, you need to change your dimension your specifying for the innner loop. When you call size() the first input is the matrix, and the second input is the dimension. 1 is rows, 2 is columns, 3 is sheets, etc.
Joana Santos
Joana Santos 2019 年 3 月 1 日
編集済み: Joana Santos 2019 年 3 月 1 日
Thank you so much! You helped me a lot :)
Have a nice day xx

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by