Help with this code - logical indexing and num2cell -
Afficher commentaires plus anciens
Hi everyone ! Would you mind taking a look at this code and explaining it to me-specifically the lines marked.
But first here is what the code does:
The function replace_me is defined like this:
function w = replace_me(v,a,b,c).
The first input argument v is a vector, while a, b, and c are all scalars. The function replaces every element of v that is equal to a with b and c. For example, the command
>> x = replace_me([1 2 3],2,4,5);
makes x equal to [1 4 5 3]. If c is omitted, it replaces occurrences of a with two copies of b. If b is also omitted, it replaces each a with two zeros.
function [result] = replace_me(v,a,b,c)
if nargin == 3
c = b;
end
if nargin == 2
c = 0;
b = 0;
end
result = v;
equ = result == a; %here
result = num2cell(result); %here
result(equ) = {[b c]}; %here
result = [result{:}]; %here
end
1 commentaire
Stephen23
le 20 Juil 2015
You can also use strrep to do this:
>> strrep([1,2,3],2,[4,5])
ans =
1 4 5 3
Réponses (1)
The line that you mention defines a vector equ of logical elements which are true (1) where the condition is true (relational operator ==) and false (0) otherwise. Arrays of logicals can be used for indexing arrays (numeric or cell). This is what is done then in the following:
result(equ) = {[b c]};
There are several things here that you can study for understanding the code better:
- The logical type/class.
- Relational operators.
- Logical indexing.
These three topics are well developed in MATLAB help/doc. To give you an example, let's define a numeric array:
>> x = [1, 8, 3, 5, 7, 2] ;
Now we apply a relational operator > (greater than) between x and the value 3, and we save the outcome of the test in a variable named isGt3 :
>> isGt3 = x > 3
isGt3 =
0 1 0 1 1 0
You can see that elements of isGt3 are 0 where the relation is false, and 1 where it is true. But these 0 and 1 are not numbers:
>> class( isGt3 )
ans =
logical
They are booleans, symbolized/represented by symbols 0 and 1. Now it is interesting to note that you can use this vector of logicals for performing logical indexing, which is extracting all elements associated with a logical index that is true:
>> x(isGt3)
ans =
8 5 7
and here you see elements at indices 2, 4, 5 of isGt3 which are true, indexed/addressed/extracted elements of x with same indices.
Catégories
En savoir plus sur Performance and Memory dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!