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

  • MATLAB
  • Thread starter ihasfigs
  • Start date
  • #1
1
0

Main Question or Discussion Point

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.
 

Answers and Replies

  • #2
1,430
1,270
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:
Code:
n=100; countr = 0; flag = 0;
while(true)
    try
        for i=1:n
            a = arr(i,:); %dummy variable storing row
            countr = countr + 1;
        end
    catch exc
            flag = 1;
    end
    if (flag == 1)
          break; %from the while loop
    end
    n = n + 100; %this statement will be reached only if the exception was not thrown
end
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.
 

Related Threads on Counting the number of rows/cols in a matrix with Matlab

  • Last Post
Replies
10
Views
82K
Replies
2
Views
4K
Replies
1
Views
5K
Replies
5
Views
16K
Replies
1
Views
9K
Replies
1
Views
8K
  • Last Post
Replies
1
Views
6K
Replies
0
Views
7K
Top