# converting a matrix into a column vector using only while-end loop

4 views (last 30 days)
Hrvoje Sarinic on 27 Apr 2022
Commented: Jan on 28 Apr 2022
Hi all, I'm trying to convert a matrix into a column vector. I also need to do this only using while loops. Please help. Here is my code:
function [A] = func4(M)
[m,n] = size(M);
A = zeros(m*n,1);
i = 1;
j = 1;
c = m*n;
while i <= m
cx = c;
A(cx,1) = M(m, n);
while j <= n
A(j,1) = M(i, j)
j = j + 1;
end
break
end
M = [1 2 3; 4 5 6]
B = func4(M)
##### 2 CommentsShowHide 1 older comment
Hrvoje Sarinic on 28 Apr 2022
Yes. I'm doing it for my college. They want us to make a function which, when executed, does the same thing you described (M = A(:)).

Jan on 27 Apr 2022
Edited: Jan on 28 Apr 2022
This sounds like a homework question and you have shown, what you have tried so far.
function A = func4(M)
[m,n] = size(M);
A = zeros(m*n, 1);
The start is fine. An alternative would be to obtain the number of elements directly by numel(M), but size() is okay.
% [EDITED] Former code collected the elements in rowwise order,
% now it is columnwise: i and j are interchanged.
k = 1; % additional counter for the output
c = m*n;
i = j;
while j <= n
i = 1; % Reset j counter inside the loop
while i <= m
A(k) = M(i, j); % k counter for A, i & j counter for M
i = i + 1;
k = k + 1;
end
j = j + 1;
end
end
The break is not needed. The only problem was the k counter for the output and the missing increasing of the i counter.
Jan on 28 Apr 2022
@Jon: You are right. I've interchanged i and j now to fix this.

### Community Treasure Hunt

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

Start Hunting!