Not compatable with the size

2 visualizaciones (últimos 30 días)
SANDIPKUMAR ROYADHIKARI
SANDIPKUMAR ROYADHIKARI el 12 de Dic. de 2021
Comentada: Walter Roberson el 12 de Dic. de 2021
I wrote the following code
clear all
clc
itr=0; % number of iteration
for t=1:1:3
itr=itr+1;
b(itr, :)=[sin(t) cos(t)];
c(itr,:)=[t 1-t^2];
d(itr,:)=[b;c];
end
I got the following error
Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.
Error in bla5 (line 11)
d(itr,:)=[b;c];
Please help me fix it

Respuestas (1)

Walter Roberson
Walter Roberson el 12 de Dic. de 2021
b(itr, :)=[sin(t) cos(t)];
c(itr,:)=[t 1-t^2];
First iteration, b and c each become 1 x 2 because they were not preallocated and are being assigned 1 x 2
d(itr,:)=[b;c];
b and c are 1x2 each on the first iteration . [b;c] would be 2 x 2, by vertically stacking the 1x2. So the right side is 2x2. And that is being assigned to a location that is constrained to have a single row and so can only be 1 x something.
If you get past this step then in the next iteration b and c each grow to 2x2 and stacking them would be 4x2...
  2 comentarios
SANDIPKUMAR ROYADHIKARI
SANDIPKUMAR ROYADHIKARI el 12 de Dic. de 2021
I need little more explanation
Walter Roberson
Walter Roberson el 12 de Dic. de 2021
Take an example time at iteration 1
t = sym(pi)/3
t = 
itr = 1
itr = 1
b(itr, :)=[sin(t) cos(t)]
b = 
You can see that b is now 1 x 2 -- because [sin(t) cos(t)] produces a vector of length 2
c(itr,:)=[t 1-t^2]
c = 
Likewise, [t 1-t^2] produces a 1 x 2 vector, so c is now a 1 x 2 vector
size(b)
ans = 1×2
1 2
size(c)
ans = 1×2
1 2
We confirm those sizes. Now let us calculate the right hand side of your next assignment statement:
rhs = [b;c]
rhs = 
size(rhs)
ans = 1×2
2 2
It is 2 x 2.
Now what happens when we try to store it to d(iter,:) . iter is a scalar value, so d(iter,:) selects a single row inside d
d(itr,:) = rhs
Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.

Error in sym/privsubsasgn (line 1229)
L_tilde2 = builtin('subsasgn',L_tilde,struct('type','()','subs',{varargin}),R_tilde);

Error in sym/subsasgn (line 1060)
C = privsubsasgn(L,R,inds{:});
The destination on the left was a single row inside d, but the source rhs had 2 rows. You cannot fit two rows into a place that only accepts one row.
Note that the result would have been different if you had been asking for
d(itr,:) = [b,c];
[b,c] asks to place the two 1 x 2 vectors beside each other, forming a 1 x 4 vector.

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by