Is there an idiomatic way to exchange two elements in an array of cells?

I know that I can write it like this:

tmp = arr{i} arr{i} = arr{j} arr{j} = tmp 

But is there an easier way? For example, in Python, I would write:

 arr[i], arr[j] = arr[j], arr[i] 
+5
source share
2 answers

Standard, idiomatic way :

Use the index vector:

 arr([ij]) = arr([ji]); %// arr can be any array type 

This works if arr is an array of cells, a numeric array, or a string (char array).


Not recommended (but possible):

If you want to use a syntax that is more similar to the syntax in Python (with a list of elements instead of an index vector), you will need a deal . But the resulting statement is more complex and varies depending on whether arr a cell array or a standard array. Therefore, it is not recommended (for the exchange of two elements). I include it for completeness only:

 [arr{i}, arr{j}] = deal(arr{j}, arr{i}); %// for a cell array [arr(i), arr(j)] = deal(arr(j), arr(i)); %// for a numeric or char array 
+8
source

Not to confuse things, but let me have one more syntax:

 [arr{[i,j]}] = arr{[j,i]}; 

or

 [arr{i},arr{j}] = arr{[j,i]}; 

The idea here is to use comma-separated lists with indexing italic shapes.

Remember that when working with cell arrays, () -indexing gives a sliced ​​array of cells, while {} -indexing extracts elements from an array of cells, and the return type is what was stored in the specified cell (when the index is not scalar, MATLAB returns each element cells separately as a comma separated list).

+2
source

Source: https://habr.com/ru/post/1202066/


All Articles