简体   繁体   中英

How do I make this specific code run faster in Matlab?

I have an array with a set of chronological serial numbers and another source array with random serial numbers associated with a numeric value. The code creates a new cell array in MATLAB with the perfectly chronological serial numbers in one column and in the next column it inserts the associated numeric value if the serial numbers match in both original source arrays. If they don't the code simply copies the previous associated value until there is a new match.

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

h = waitbar(0,'Please Wait...');
steps = length(serial);

for k = 1:length(serial)

    [row1, col1, vec1] = find(B == serial{k,1});
    tf1 = isempty(vec1);

    if (tf1 == 0)
        prices = random{col1,2}; 
        data(j,2) = num2cell(value);
        j = j + 1;
    else
        data(j,2) = num2cell(value);
        j = j + 1;
    end

    waitbar(k/steps,h,['Please Wait... ' num2str(k/steps*100) ' %'])

end

close(h);

Right now, the run-time for the code is approximately 4 hours. I would like to make this code run faster. Please suggest any methods to do so.

UPDATE

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

Firstly, run the MATLAB profiler (see 'doc profile') and see where the bulk of the execution time is occuring.

Secondly, don't update the waitbar on every iteration> Particularly if serial contains a large (> 100) number of elements.

Do something like:

if (mod(k, 100)==0) % update on every 100th iteration
     waitbar(k/steps,h,['Please Wait... ' num2str(k/steps*100) ' %'])
end

Some points:

Firstly it would help a lot if you gave us some sample input and output data.

Why do you initialize data as one column and then fill it's second in the loop? Rather initialize it as 2 columns upfront: data = cell(length(serial), 2);

Is j ever different from k , they look identical to me and you could just drop both the j = j + 1 lines.

tf1 = isempty(vec1); if (tf1 == 0)... tf1 = isempty(vec1); if (tf1 == 0)... is the same as the single line: if (!isempty(vec1)) or even better if(isempty(vec1)) and then swap the code from your else and your if .

But I think you can probably find a fast vecotrized solution if you provide some (short) sample input and output data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM