two dimensional array indexing

2 次查看(过去 30 天)
Natalie Huynh
Natalie Huynh 2019-10-16
Hello,
I am doing a homework assignment where I have to write a function that gets a randomly generated 2 dimensional array, a character (r for row and c for column), and a number of the row or column. The function then returns the row or column based off of the information inputted. It also returns an empty array when either there is a wrong input argument for the character (aka something that is not r or c) or when the row or column number doesn't exist.
The following code below is what I have done, and it passes all the tests besides checking if the expected output is obtained when all the correct information is put in. I am wondering if I can get some help on where I may have done something wrong.
function output = twoDimensionalIndexingFn(inArray, rowOrColumn, vectNumber)
newROrC = upper(rowOrColumn);
if (any(vectNumber <= 0))
output = [];
elseif (newROrC ~= 'R') || (newROrC ~= 'C')
output = [];
elseif (newROrC == 'R')
output = inArray(vectNumber, :);
elseif (newROrC == 'C')
output = inArray(:, vectNumber);
end
end
  2 个评论
Basil C.
Basil C. 2019-10-16
Could you elaborate on what you mean by "checking if the expected output is obtained when all the correct information is put in" because the code seems fine by me.
You could also add a condition to check that the variable vectNumber lies within the size of the inArray
if (any(inArray <= 0))
output = [];
elseif (newROrC == 'R'&& vectNumber <= size(inArray,1))
output = inArray(vectNumber, :);
elseif (newROrC == 'C'&& vectNumber <= size(inArray,2))
output = inArray(:, vectNumber);
else
output=[]
end
Natalie Huynh
Natalie Huynh 2019-10-16
What I meant by that was if the user were to put in a valid inArray, valid character (r or c), and valid vectNumber. I tested the condition that you suggested and it worked. I think that I had to be more specific with the row or column number "does not exist" portion of the instructions. I only had it set to if any of the elements in inArray that were less than or equal to 0 instead of having it set to specifically the dimensions of the array.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by