Inserting zeros for missing values in a vector
显示 更早的评论
% 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
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!