Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8457049
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T12:42:28+00:00 2026-06-10T12:42:28+00:00

Please help me to improve the following Matlab code to improve execution time. Actually

  • 0

Please help me to improve the following Matlab code to improve execution time.

Actually I want to make a random matrix (size [8,12,10]), and on every row, only have integer values between 1 and 12. I want the random matrix to have the sum of elements which has value (1,2,3,4) per column to equal 2.

The following code will make things more clear, but it is very slow.
Can anyone give me a suggestion??

clc
clear all
jum_kel=8
jum_bag=12
uk_pop=10

for ii=1:uk_pop;    
    for a=1:jum_kel
        krom(a,:,ii)=randperm(jum_bag); %batasan tidak boleh satu kelompok melakukan lebih dari satu aktivitas dalam satu waktu
    end
end

for ii=1:uk_pop;  
gab1(:,:,ii) = sum(krom(:,:,ii)==1)
gab2(:,:,ii) = sum(krom(:,:,ii)==2)
gab3(:,:,ii) = sum(krom(:,:,ii)==3)
gab4(:,:,ii) = sum(krom(:,:,ii)==4)
end

for jj=1:uk_pop;
     gabh1(:,:,jj)=numel(find(gab1(:,:,jj)~=2& gab1(:,:,jj)~=0))
     gabh2(:,:,jj)=numel(find(gab2(:,:,jj)~=2& gab2(:,:,jj)~=0))
     gabh3(:,:,jj)=numel(find(gab3(:,:,jj)~=2& gab3(:,:,jj)~=0))
     gabh4(:,:,jj)=numel(find(gab4(:,:,jj)~=2& gab4(:,:,jj)~=0))
end

for ii=1:uk_pop;
    tot(:,:,ii)=gabh1(:,:,ii)+gabh2(:,:,ii)+gabh3(:,:,ii)+gabh4(:,:,ii)
end

for ii=1:uk_pop;
    while tot(:,:,ii)~=0;
          for a=1:jum_kel
              krom(a,:,ii)=randperm(jum_bag); %batasan tidak boleh satu kelompok melakukan lebih dari satu aktivitas dalam satu waktu
          end
          gabb1 = sum(krom(:,:,ii)==1)
          gabb2 = sum(krom(:,:,ii)==2)
          gabb3 = sum(krom(:,:,ii)==3)
          gabb4 = sum(krom(:,:,ii)==4)

          gabbh1=numel(find(gabb1~=2& gabb1~=0));
          gabbh2=numel(find(gabb2~=2& gabb2~=0));
          gabbh3=numel(find(gabb3~=2& gabb3~=0));
          gabbh4=numel(find(gabb4~=2& gabb4~=0));

          tot(:,:,ii)=gabbh1+gabbh2+gabbh3+gabbh4;
    end
end
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T12:42:29+00:00Added an answer on June 10, 2026 at 12:42 pm

    Some general suggestions:

    • Name variables in English. Give a short explanation if it is not immediately clear,
      what they are indented for. What is jum_bag for example? For me uk_pop is music style.
    • Write comments in English, even if you develop source code only for yourself.
      If you ever have to share your code with a foreigner, you will spend a lot of time
      explaining or re-translating. I would like to know for example, what
      %batasan tidak boleh means. Probably, you describe here that this is only a quick
      hack but that someone should really check this again, before going into production.

    Specific to your code:

    • Its really easy to confuse gab1 with gabh1 or gabb1.
    • For me, krom is too similar to the built-in function kron. In fact, I first
      thought that you are computing lots of tensor products.
    • gab1 .. gab4 are probably best combined into an array or into a cell, e.g. you
      could use

      gab = cell(1, 4);
      for ii = ...
          gab{1}(:,:,ii) = sum(krom(:,:,ii)==1);
          gab{2}(:,:,ii) = sum(krom(:,:,ii)==2);
          gab{3}(:,:,ii) = sum(krom(:,:,ii)==3);
          gab{4}(:,:,ii) = sum(krom(:,:,ii)==4);
      end
      

      The advantage is that you can re-write the comparsisons with another loop.
      It also helps when computing gabh1, gabb1 and tot later on.

      If you further introduce a variable like highestNumberToCompare, you only have to
      make one change, when you certainly find out that its important to check, if the
      elements are equal to 5 and 6, too.

    • Add a semicolon at the end of every command. Having too much output is annoying and
      also slow.

    • The numel(find(gabb1 ~= 2 & gabb1 ~= 0)) is better expressed as
      sum(gabb1(:) ~= 2 & gabb1(:) ~= 0). A find is not needed because you do not care
      about the indices but only about the number of indices, which is equal to the number
      of true‘s.

    • And of course: This code

      for ii=1:uk_pop
          gab1(:,:,ii) = sum(krom(:,:,ii)==1)
      end
      

      is really, really slow. In every iteration, you increase the size of the gab1
      array, which means that you have to i) allocate more memory, ii) copy the old matrix
      and iii) write the new row. This is much faster, if you set the size of the
      gab1 array in front of the loop:

      gab1 = zeros(... final size ...);
      for ii=1:uk_pop
          gab1(:,:,ii) = sum(krom(:,:,ii)==1)
      end
      

      Probably, you should also re-think the size and shape of gab1. I don’t think, you
      need a 3D array here, because sum() already reduces one dimension (if krom is
      3D the output of sum() is at most 2D).

      Probably, you can skip the loop at all and use a simple sum(krom==1, 3) instead.
      However, in every case you should be really aware of the size and shape of your
      results.

    Edit inspired by Rody Oldenhuis:

    As Rody pointed out, the ‘problem’ with your code is that its highly unlikely (though
    not impossible) that you create a matrix which fulfills your constraints by assigning
    the numbers randomly. The code below creates a matrix temp with the following characteristics:

    • The numbers 1 .. maxNumber appear either twice per column or not at all.
    • All rows are a random permutation of the numbers 1 .. B, where B is equal to
      the length of a row (i.e. the number of columns).

    Finally, the temp matrix is used to fill a 3D array called result. I hope, you can adapt it to your needs.

    clear all;
    A = 8; B = 12; C = 10;
    % The numbers [1 .. maxNumber] have to appear exactly twice in a
    % column or not at all.
    maxNumber = 4;
    result = zeros(A, B, C);
    for ii = 1 : C
        temp = zeros(A, B);
        for number = 1 : maxNumber
            forbiddenRows = zeros(1, A);
            forbiddenColumns = zeros(1, A/2);
            for count = 1 : A/2
                illegalIndices = true;
                while illegalIndices
                    illegalIndices = false;
                    % Draw a column which has not been used for this number.
                    randomColumn = randi(B);
                    while any(ismember(forbiddenColumns, randomColumn))
                        randomColumn = randi(B);
                    end
                    % Draw two rows which have not been used for this number.
                    randomRows = randi(A, 1, 2);
                    while randomRows(1) == randomRows(2)  ...
                          || any(ismember(forbiddenRows, randomRows))
                      randomRows = randi(A, 1, 2);
                    end
                    % Make sure not to overwrite previous non-zeros.
                    if any(temp(randomRows, randomColumn))
                        illegalIndices = true;
                        continue;
                    end
                end
                % Mark the rows and column as forbidden for this number.
                forbiddenColumns(count) = randomColumn;
                forbiddenRows((count - 1) * 2 + (1:2)) = randomRows;
                temp(randomRows, randomColumn) = number;
            end
        end
    
        % Now every row contains the numbers [1 .. maxNumber] by 
        % construction. Fill the zeros with a permutation of the
        % interval [maxNumber + 1 .. B].
        for count = 1 : A
            mask = temp(count, :) == 0;
            temp(count, mask) = maxNumber + randperm(B - maxNumber);
        end
    
        % Store this page.
        result(:,:,ii) = temp;
    end
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Please help me to improve the following script: http://jsfiddle.net/n9BkM/8/ I need the following fucntionality:
please help me to identify which of these following is more optimized code? for(int
Please help me understand the following code snippet :- def any(l): whether any number
Please help to improve the following query: UPDATE queries q SET query = (SELECT
Could someone please help meto improve this part of code? The string is something
please help me. I want know about what types of flags to run an
I have been trying to find ways to make the following piece of code
please help me out for the below problem, i am trying since long time(3
Please tell me why this program is not working?? help me improve it. for
Please help me understand if the following choices I have made are idiomatic/good and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.