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

3 visualizzazioni (ultimi 30 giorni)
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 Commenti
Jon
Jon il 27 Apr 2022
First of all you can do the whole thing with just one statement
M = A(:)
Even if you were going to do it with loops it would be better to use a for loop than a while as you already know how many iterations you need to do.
Is this for a homework problem that requires you to use while loops?
Hrvoje Sarinic
Hrvoje Sarinic il 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(:)).

Accedi per commentare.

Risposta accettata

Jan
Jan il 27 Apr 2022
Modificato: Jan il 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.
  5 Commenti
Jon
Jon il 28 Apr 2022
One other point. If you truly want to emulate A = M(:), then you should note that this operation turn the matrix into a column, "columnwise", meaning it stacks the columns of M. So for your example you would get A (1) = 1 A(2) = 4, A(3) = 2, A(4) = 5 etc.
I think the code above goes "rowwise", so it stacks the rows of M, and you get A (1) = 1 A(2) = 2,... A(4) = 4 etc
Jan
Jan il 28 Apr 2022
@Jon: You are right. I've interchanged i and j now to fix this.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by