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

조회 수: 1 (최근 30일)
when i try to run the follwing code, is shows the error as
Unable to perform assignment because the left and right sides have a different number of elements.
in the line "y(j)=x(j)+sigma.*randn(size(j));"
Help me out to rectify this..
Code:
Var=numel(x);
nMu=ceil(mu*nVar);
j=randsample(nVar,nMu);
if numel(sigma)>1
sigma = sigma(j);
end
y=x;
y(j)=x(j)+sigma.*randn(size(j));
Thanks in advance..

답변 (2개)

KSSV
KSSV 2021년 2월 5일
This error happens when you try to save more number of elements than initialized.
Example:
A = zeros(1,3) ;
A(1) = rand(1,2) % this will give error
In the above you need to save only one element in A(1) but you are saving two, so error pops out.
A = zeros(1,3) ;
k = []; % empty matrix
A(1) = [] % error
The above also throws error. I included this example keeping @Walter Roberson sir's comment.
Check your code and rethink on it.

Walter Roberson
Walter Roberson 2021년 2월 5일
Oh wait... is it possible that x is a row vector? If so then with vector j, no matter whether j is a row vector or column vector, x(j) would be a row vector because x is a row vector. Vector being indexed by vector gives orientation the same as the source vector, not the orientation of the indexing vector.
randsample() in that form returns a column vector, so j is a column vector.
x(j)+sigma.*randn(size(j))
^^^^ ^^^^^ ^^^^^^^^^^^^^^
row scalar column
and row + column gives a 2D array . You would get an nMu x nMu output array, not a 1 x nMu output array.
y(j) = reshape(x(j),[],1) + reshape(sigma.*randn(size(j)), [], 1);
Or if you are sure that x is a row vector, then
y(j) = x(j).' + sigma.*randn(size(j));

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by