Assign a row vector to a row of an array using logical indexing to omit certain values
Show older comments
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?
Accepted Answer
More Answers (2)
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
1 Comment
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."
In many places in MATLAB, the values 0 and false can be used interchangeably.
x1 = 5+0
x2 = 5+false
Indexing is one of the exceptions where they are treated differently.
x = 1:10
x([false true true]) = [42, -999] % works
x([0 1 1]) = [42, -999] % throws an error
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 Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!