MATLAB Counting the number of rows/cols in a matrix with Matlab

  • Thread starter ihasfigs
  • Start date
I'm taking a course that uses matlab, and for one assignment, we need to write a function that, among other things, counts the number of rows and columns in any given numeric matrix. The thing is that we're not allowed to use any built-in functions. No x = size(mat). No length(mat). It all has to be done with loops.
I was thinking of writing 2 while loops; one to count the number of columns and one to count the number of rows. The only problem is that I have no idea how to check whether or not a specified row or column exists. I tried the 'exist' function, but that will only tell me if the matrix exists.
any help is appreciated.

Wrichik Basu

Gold Member
2018 Award
I don't know why schools give such things. You can do this work with exception handling, but you have to guess a large number, such that the dimensions of your array are smaller than that.

Try this code:
n=100; countr = 0; flag = 0;
        for i=1:n
            a = arr(i,:); %dummy variable storing row
            countr = countr + 1;
    catch exc
            flag = 1;
    if (flag == 1)
          break; %from the while loop
    n = n + 100; %this statement will be reached only if the exception was not thrown
The logic is that if you ask for an index of the array that is greater than the dimensions of the array, matlab will give an exception. The catch clause will catch that exception. The flag will check whether the exception was thrown or not. If the exception was not thrown (flag = 0 after program executes), the number (n) you guessed was smaller than the size of the array, and increment that number by 100 or so, and continue the loop.

You can construct a similar program for the number of columns, replacing countr with countc. Remember to initialise countc to 0. Use a = arr(:,i) for taking in the columns.

Want to reply to this thread?

"Counting the number of rows/cols in a matrix with Matlab" You must log in or register to reply here.

Physics Forums Values

We Value Quality
• Topics based on mainstream science
• Proper English grammar and spelling
We Value Civility
• Positive and compassionate attitudes
• Patience while debating
We Value Productivity
• Disciplined to remain on-topic
• Recognition of own weaknesses
• Solo and co-op problem solving