필터 지우기
필터 지우기

Assign a row vector to a row of an array using logical indexing to omit certain values

조회 수: 4 (최근 30일)
I have a function, , that outputs a vector of numerical values, I also have two matrices, , the former matrix is an array of zeros, for pre-allocation, whose width is of equal length to the vector output of my function, the latter is an array of equal size and composed of logical values. I want to the iterate through the rows of Q and assign them the output of but only in the positions of G corresponding with a value of 1. I've tried the following
[H,~] = size(Q);
for i=1:H
goodVals = G(i,:);
out = myFunc;
Q(i,goodVals) = out;
end
But I get the error: Array indices must be positive integers or logical values. Is there an smooth way of doing what I'm trying to do without reshaping my arrays? If not what is the shortest and cleanest way of accomplishing this?

채택된 답변

David Gillcrist
David Gillcrist 2023년 2월 27일
I feel embarassed to answer my own question only a short while after giving it some though, but the solution is quite simple really. You just need to take the element-wise product of the row of G with the output of , and assign it to the whole row of Q. Like so:
[H,~] = size(Q);
for i=1:H
goodVals = G(i,:);
out = myFunc;
Q(i,:) = out.*goodVals;
end

추가 답변 (2개)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2023년 2월 27일
As you stated that Q and G are zero matrices generated for memoty allocation if so, and you want to to fill out the values of Q respectively with G. Then the solution code is this one:
Q = zeros(7,3);
[H,~] = size(Q);
for ii=1:H
out = myFunc;
Q(ii,:) = out;
end
function OUT = myFunc(~)
OUT = randi(10,1);
end
  댓글 수: 1
Dyuman Joshi
Dyuman Joshi 2023년 2월 27일
G is not a zero matrix - "... the latter is an array of equal size and composed of logical values."

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


Steven Lord
Steven Lord 2023년 2월 27일
In many places in MATLAB, the values 0 and false can be used interchangeably.
x1 = 5+0
x1 = 5
x2 = 5+false
x2 = 5
Indexing is one of the exceptions where they are treated differently.
x = 1:10
x = 1×10
1 2 3 4 5 6 7 8 9 10
x([false true true]) = [42, -999] % works
x = 1×10
1 42 -999 4 5 6 7 8 9 10
x([0 1 1]) = [42, -999] % throws an error
Array indices must be positive integers or logical values.
You could make G a logical array by calling logical on it or allocating it as a false array before assigning values into its elements. In that case the size of the array you're assigning into Q would need to be based on the number of true values in the index vector rather than the number of elements. In the example above, the logical index vector [false true true] had 3 elements but only 2 of them were true, so I could only assign 2 elements to those locations.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by