Unable to perform assignment because the left and right sides have a different number of element

1 次查看(过去 30 天)
hey
im new to matlab and i have problem i dont find how i can Increases the array size in a loop
i have tryed to use ones without succses
i will explain my code :
i have 6 game cube (1:6) and i have to throw all of them
i have to display all possible option which i did with sucsess i dont know if its the best option
but i also need to display all result that equal to 20 or bigger then 30 - here i need help
here is my code so far :
dbstop if error
cube=[1 2 3 4 5 6];
A=zeros(6^6,6); % number of the option
K=zeros(s,6);
L=zeros(s,6);
s=numel(A);
b20=0; % throwing cube ==20
b30=0; %;throwing cube >30
n=0; % counter
m=0; % counter
for i1=1:6
for i2=1:6
for i3=1:6
for i4=1:6
for i5=1:6
for i6=1:6
A=[i1 i2 i3 i4 i5 i6];
disp(A);
if (i1+i2+i3+i4+i5+i6)==20
b20=b20+1;
n=n+1;
K(n)=A;
elseif (i1+i2+i3+i4+i5+i6)>30
b30=b30+1;
m=m+1;
L(n)=A;
end
end
end
end
end
end
end
i will appriciate any help and improvment to my code

采纳的回答

Jan
Jan 2021-3-22
编辑:Jan 2021-3-22
K(n, :) = A;
% ^
L(n, :) = A;
% ^
The vector A can be assigne to the vector of the array K and L only. K(n) is a scalar, the same as K(n, 1).
Another problem:
K=zeros(s,6); % s is used
L=zeros(s,6);
s=numel(A); % but defined later only.
% But you do not need numal(A) outputs, but size(A, 1) only
Pre-allocating A by "A=zeros(6^6,6);" is not needed, if you overwrite it in the code:
A=[i1 i2 i3 i4 i5 i6];
The variable n and b20 as well as m and b30 have the same values. To you can omit n and m, or b20 and b30.
The variable cube is not used anywhere. So you can omit the line "cube=[1 2 3 4 5 6];"
  4 个评论
the cyclist
the cyclist 2021-3-25
I was thinking of an array where n is larger than size(K,1), for example:
n = 5;
K = rand(3,6);
K(n) % Correct linear indexing
ans = 0.5661
K(n,1) % Error with subscript indexing
Index in position 1 exceeds array bounds (must not exceed 3).
Jan
Jan 2021-3-25
Yes, now I understand your comment. Thanks for the explanation. Sometimes experiences block my view on trivial bugs, because I would avoid them intuitively.

请先登录,再进行评论。

更多回答(1 个)

the cyclist
the cyclist 2021-3-22
You need to use
K(n,:)=A;
and
L(n,:)=A;
to assign the row vector A to a row of K or L.
K(n) is a single element, using linear indexing.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by