Inserting zeros for missing values in a vector
4 ビュー (過去 30 日間)
古いコメントを表示
% 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
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
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
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 件のコメント
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 Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!