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

AI Thread Summary
The discussion revolves around creating a MATLAB function to count the number of rows and columns in a numeric matrix without using built-in functions like size or length. The proposed solution involves using two while loops, one for counting rows and another for columns, by leveraging exception handling. The approach suggests initializing a variable to a large number and attempting to access matrix indices within a try-catch block. If an index exceeds the matrix dimensions, an exception is thrown, which is caught to determine the actual size of the matrix. The logic involves incrementing the guessed index until an exception occurs, indicating the maximum valid index. This method allows for counting both rows and columns effectively while adhering to the assignment's constraints.
ihasfigs
Messages
1
Reaction score
0
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.
 
Physics news on Phys.org
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.
 
Back
Top