Using two vectors to get the third one
3 次查看(过去 30 天)
显示 更早的评论
Please I have these three columns where the first line is hour but not all the hours in a day, the second line is data of the corresponding first hours. I have the third line as hours complete.
I want to use the third line, any hour thats is not represented in the first line should be represented with nan in the second line, e.g
0 34 0
1 23 1
2 34 2
4 12 3
5 13 4
7 4.6 5
8 0.4 6
9 -3.8 7
10 -8 8
12 -16.4 9
13 -20.6 10
14 -24.8 11
16 -33.2 12
17 -37.4 13
18 -41.6 14
20 -50 15
21 -54.2 16
23 -62.6 17
18
19
20
21
22
23
2 个评论
the cyclist
2019-10-7
How are the data currently stored? When you say "these three columns", do you mean you have three different vectors?
采纳的回答
Joe Vinciguerra
2019-10-7
x = [0,1,2,4,5,7,8,9,10,12,13,14,16,17,18,20,21,23]; % here's your first column
y = x*rand()+rand(); % here's a vague representation of your second column
z = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]; % here's your third column
index = (ismember(z,x)); % find which values in z are in x
yPrime = zeros(length(index),1); % preallocate a new variable
skip = 0; % We need a counter to count every time we skip a value to make the array sizes work out
for i = 1:length(index)
if index(i) % if the number exists...
yPrime(i) = y(i-skip); % stuff it in a new variable
else % if it doesn't exist
yPrime(i) = NaN; % set it to NaN
skip = skip + 1; % and count it
end
end
8 个评论
Walter Roberson
2019-10-9
Joe Vinciguerra comments to Toyese Ayorinde
This code works with file provided, and does what was requested. This question should be closed. Toyese, if you have addition issues you should ask a new question and provide details about what you are trying to accomplish and specifically what the issue you are having is. Thank you.
更多回答(2 个)
the cyclist
2019-10-7
编辑:the cyclist
2019-10-7
This is virtually equivalent to Fangjun's solution. But it uses some intuitive variable names (and comments) to help you understand what it going on.
The first three lines are where you would have your actual vectors.
%%% This part is just setting up some input data that are like what you describe
incompleteHours = [0; 1; 2; 4; 5; 7]; % Your "first line" hours
data = rand(size(incompleteHours)); % Your "second line" data
completeHours = (0:23)'; % Your "third line" with the complete list of hours
%%% This part is the actual solution, using those inputs
% Preallocate the output with NaN. (We'll fill in the data later)
dataForCompleteHours = nan(size(completeHours));
% Identify the hours we have, and their index to the data
[~,idx] = ismember(incompleteHours,completeHours);
% Fill in the data
dataForCompleteHours(idx) = data;
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!