Cell Arrays and Indexing?

조회 수: 49 (최근 30일)
James Metz
James Metz 2020년 4월 4일
편집: James Tursa 2020년 4월 4일
The goal of my code is to take an n-by-n logical array of values and output a cell vector containing the column indices of each true (1) element in the input matrix. The row index of the logical true values is the index of the cell in the cell vector, and the column index is the value(s) within the cell of the corresponding cell in the cell vector.
Here's an example of how it's supposed to work:
function output = input(A)
A =
0 1 0 1
1 1 0 1
1 0 1 0
0 0 0 0
output =
{[2 4], [1 2 4], [1 3], []}
Here's my code:
function opp = hw5_problem5(X)
opp = []; % initialize the matrix to empty
[~, col] = size(X); % setting the size of X to variable so it can change with input
for ii = 1:col
if X(ii) == 1
opp(ii) = opp; {ii}; % add previous cells of opp to new cells as iterations continue
else
opp(ii) = []; % if value of X(ii) == 0 no new values added to opp
end
end
end
I keep getting this error message:
Unable to perform assignment because the indices on the left side are not compatible with the size of the
right side.
Error in hw5_problem5 (line 6)
opp(ii) = opp, {ii}; %add previous cells of opp to new cells as iterations continue
Help please! Thanks :)
  댓글 수: 1
James Tursa
James Tursa 2020년 4월 4일
You need to loop over the rows, not the columns. See below.

댓글을 달려면 로그인하십시오.

채택된 답변

James Tursa
James Tursa 2020년 4월 4일
편집: James Tursa 2020년 4월 4일
This is the reverse of your last assignment. It needs only one loop over the number of rows, and the cell array element for that row contains the column indexes of the 1 elements. You should look into the find( ) function. The inside of your loop needs only one line of code.
  댓글 수: 3
James Metz
James Metz 2020년 4월 4일
편집: James Metz 2020년 4월 4일
Ok, this is what it boils down to I think, but I'm still not sure what is wrong with it. When I input the simple matrix c shown below, that's the output I get.
function opp = hw5_problem5(X)
opp = [];
[rows, ~] = size(X);
for ii = 1:rows
opp = [opp {find(X(ii) == 1)}];
end
end
c = [false true; true false]
output = {[], [1]}
The second cell is correct, but why isn't the first? Does find(X(ii) == 1) not output the index 2?
James Tursa
James Tursa 2020년 4월 4일
편집: James Tursa 2020년 4월 4일
You are pretty close, but ask yourself what does X(ii) mean? Is it the ii'th row of X? No, it isn't. It is the ii'th element of X using linear indexing. The ii'th row of X is X(ii,:).

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Ameer Hamza
Ameer Hamza 2020년 4월 4일
This is an alternative to the looped version
A = [0 1 0 1
1 1 0 1
1 0 1 0
0 0 0 0];
[r, c] = find(A);
out = accumarray(r, c, [], @(x) {x});
if size(out,1) ~= size(A,1)
out{size(out,1)+1:size(A,1)} = [];
end

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by