Not compatable with the size

3 次查看(过去 30 天)
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

回答(1 个)

Walter Roberson
Walter Roberson 2021-12-12
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 个评论
Walter Roberson
Walter Roberson 2021-12-12
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by