1

I have an array with a set of chronological serial numbers and another source array with random serial numbers associated with a numeric value. I wish to create a new cell array in MATLAB with the perfectly chronological serial numbers in one column and in the next I wish to insert the associated numeric value if the serial numbers match in both original source arrays. If they don't I simply want to copy the previous associated value until there is a new match.

For example

source input (serial)
1
2
3
4
5
6
7

source input (random)
1    100
2    105 
4    106
7    107

desired output (data)
SR No           Value
1               100
2               105
3               105
4               106
5               106
6               106
7               107

Right now, the problem I have is that whenever I run the code below, I end up with empty cell values where there should be repeated values inserted by a (correctly working) program, i.e. in rows with serial numbers 3, 5-29, etc.

Here's the code I've got so far:

j = 1;
A = {serial{1:end,1}};
B = cell2mat(A);
value = random(1,2);
data(:,1) = serial(:,1);

for k = 1:length(random)

    [row, col, vec] = find(B == random{k,1});
    tf = isempty(vec);

    if (tf ~= 1)
        value = random(row,2); 
        data(j,2) = random(row,2);
        j = j + 1;
    else
        data(j,2) = value;
        j = j + 1;
    end
end

How do I create this cell array without the empty values?

Note: Serial Values may be repeated in some cases - these are duplicates that cannot (or should not) be removed, but may need to be ignored by the program to avoid infinite loops.

Any suggestions on how to accomplish this would be appreciated.

4

1 回答 1

1

类似的东西?

serial = {1,2,3,4,5,6,7};
random = {1,100; 2, 105; 4, 106; 7, 107;};

data(:,1) = cell2mat(serial)';
data(:,2) = NaN;

for k=1:size(random,1)
    data(data(:,1)==random{k,1},2) = random{k,2};
end
for k=2:size(data,1)% what if there is no value for first serial number?
    if isnan(data(k,2))
        data(k,2) = data(k-1,2);
    end
end
disp(data)

顺便说一句:我建议您不要使用MATLAB 函数名称作为变量名称(即代码中的随机名称)。

于 2013-07-19T09:43:17.250 回答