Inserting zeros for missing values in a vector

조회 수: 9 (최근 30일)
Dom
Dom 2023년 4월 3일
댓글: Jon 2023년 4월 6일
% ID is an index
% IDx is a 'result' (Values in Vx conform to IDx)
% Index values 1 and 4 and missing in IDx (when compared with ID)
% I want to put a zero in Vx at positions 1 and 4
% This code works - newVx has zeros in right places
ID=[1:5]';
IDx=[2,3,5]';
Vx=[10,15,20]';
newVx=NaN( size( ID ) );
newVx (ismember(ID,IDx)) = Vx;
newVx = fillmissing(newVx,'constant',0)
%
% but if the problem is repeated (below)
% I get an error message:
% Unable to perform assignment because the left and right sides have a different number of elements.
%
ID=[1:5]';
ID2=repmat(ID,2,1);
IDx=[2,3,5,1, 4]';
Vx=[10,15,20, 30, 40]';
newVx=NaN( size( ID2 ) );
newVx (ismember(ID2,IDx)) = Vx;
newVx = fillmissing(newVx,'constant',0)
%
% In this case newVx should look like this:
% ID newVx
% 1 0
% 2 10
% 3 15
% 4 0
% 5 20
% 1 30
% 2 0
% 3 0
% 4 40
% 5 0
%
% Appreciate suggestions for a solution - my ID vector is of length 97 and is repeated 15 times(1455 x 1)
% Length of (IDx &) Vx is 1208
  댓글 수: 2
Jon
Jon 2023년 4월 4일
You could do this:
% define number of products
numProducts = 5;
% Define products and there export values
products = [2,3,5,1,4]
value = [10,15,20,30,40];
% Assume that when product list goes to a lower value we are on to the next
% country, then assign corresponding row index in full matrix
country = cumsum([1 diff(products)<0])% gives country number
rowIdx = (country-1)*numProducts + products;
% Make output data array with first column product id's second column
% export value
numCountries = max(country);
exportValues = zeros(numCountries*numProducts,2);
expValues(:,1) = repmat((1:numProducts)',2,1); % product id's
expValues(rowIdx,2) = value
Jon
Jon 2023년 4월 4일
Please note the above solution will not work if you have some countries that do not export anything, as there will be no way to detect that there is a missing country in your products vector. If you have to cover this edge case then further development will be required

댓글을 달려면 로그인하십시오.

채택된 답변

Jon
Jon 2023년 4월 3일
At line 22 on the right hand side you have the vector Vx which has 5 elements. On the left hand side you have newVx indexed by ismember(ID2,IDx). Evaluating ismember(ID2,IDx) you see that it is true for all 10 elements of ID2. So you are trying to assign a 5 element vector to a 10 element vector and MATLAB can't do that, thus the error.
  댓글 수: 7
Dom
Dom 2023년 4월 5일
Thanks Jon, That works. Appreciate your effort.
Jon
Jon 2023년 4월 6일
Your welcome, interesting problem. If this solved your problem could you please accept the answer. This way if someone else has a similar issue they will know that a solution is available.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by