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

12 views (last 30 days)
David Gillcrist on 27 Feb 2023
Edited: David Gillcrist on 27 Feb 2023
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 on 27 Feb 2023
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

Sulaymon Eshkabilov on 27 Feb 2023
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
Dyuman Joshi on 27 Feb 2023
G is not a zero matrix - "... the latter is an array of equal size and composed of logical values."

Steven Lord on 27 Feb 2023
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.

### Categories

Find more on Matrix Indexing in Help Center and File Exchange

R2022a

### Community Treasure Hunt

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

Start Hunting!