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
0 个评论
回答(1 个)
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
2021-12-12
Take an example time at iteration 1
t = sym(pi)/3
itr = 1
b(itr, :)=[sin(t) cos(t)]
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]
Likewise, [t 1-t^2] produces a 1 x 2 vector, so c is now a 1 x 2 vector
size(b)
size(c)
We confirm those sizes. Now let us calculate the right hand side of your next assignment statement:
rhs = [b;c]
size(rhs)
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
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!