Understanding :error To RESHAPE the number of elements must not change while manipulating matrix

1 view (last 30 days)
Khairul Nur
Khairul Nur on 26 Oct 2019
Edited: Guillaume on 26 Oct 2019
Hi, i need some explaination, i run this code and the input matrix 40*11 and resulted 41*11 matrix. I try to put it into a new matrix by using reshape and has error.
function [] = cacl_mean(G)
k = 4
j = 1
i=1
[numRows,numCols] = size(G) %numRows =40,numCols =11
while j <= k
for n = i:40 %iteration dr data row 1 hingga 40
if (G(i,11)) == j %check data col ke 11 ada value j=1@2@3@4
L=G(i,:)
i=i+1
else
i=i+1
end
end
n=1
i=1
disp(n)
disp(j)
j=j+1
end
kk = reshape(L,41,11); % error To RESHAPE the number of elements must not change.
end

Answers (1)

Guillaume
Guillaume on 26 Oct 2019
Edited: Guillaume on 26 Oct 2019
It's very unclear what your code is meant to do, it makes no sense.
Anyway, in your loop your creating (sometimes!) L as a vector consisting of a row of your G matrix. If the condition is true several times in your loop, this L will contain only the last row for which it is true. Also note that if the condition is never true, then L won't exist and you'll have an error telling you it's undefined later on.
So, if L exists, it's a vector corresponding to one row of G. According to your comments G has 11 columns, so L is 1x11. Obviously, it can't be reshaped into a 41x11 matrix.
You should learn to debug your programs. By stepping through your code one line at a time, you'd have seen the problem immediately.
Notes:
  • You query the size of the input matrix, a good thing to do, but then completely ignore that and hardcode it in the loop. So in the end your code only works for a 40x11 matrix.
  • Your function doesn't return anything
  • it's unclear why you're using a while loop, when for j = 1:k would be clearer.
  • It's unclear why the i=i+1 is in both branches of the if. May as well put it afterward and write the line only once.
  • More importantly it's very unclear what you meant to do with your for n=i:40, which here is exactly equivalent to for n = 1:40 since the value of i is always 1 when the loop starts. Additionally you never use n. Your loops are exactly equivalent to:
for j = 1:4
for i = 1:40 %would be better as for i = 1:numRows
if G(i, 11) == j
L = G(i, :);
end
end
end
Again, this does the same as what you wrote, only it's a lot clearer. Of course, it's unlikely to be what you meant to do.

Community Treasure Hunt

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

Start Hunting!