How to populate a matrix based on a function?
6 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Shaun Pedicini
il 4 Mar 2018
Commentato: Walter Roberson
il 23 Ago 2020
I have a 2d matrix of width 256 and height 128.
I also have some theoretical function: 127.5 * cos(pi * row_index) + col_index
I want to populate the cells of the matrix using this function so that the row_index/col_index pull from each cell as it is computed.
Ideally I need to use functions that can run against each cell in a matrix and also have access to the following variables:
- Current Column Index
- Current Row Index
- Current Cell Value (I'm not using this in the earlier example, but I'd like to be able to use it in the future)
0 Commenti
Risposta accettata
Walter Roberson
il 4 Mar 2018
[RowIndices, ColumnIndices] = ndgrid(1:size(YourArray,1), 1:size(YourArray,2));
population_function = @(col_idx, row_idx, CurrentCellValue) 127.5 * cos(pi * row_index) + col_index;
populated_matrix = arrayfun(population_function, ColumnIndices, RowIndices, YourArray);
... But you will find that it is more efficient to just use vectorization:
[col_index, row_index] = ndgrid(1:size(YourArray,1), 1:size(YourArray,2));
populated_matrix = 127.5 * cos(pi * row_index) + col_index;
4 Commenti
s s
il 23 Ago 2020
It's so cumbersome to do this in matlab compared with the Mathematica function "Table".
Walter Roberson
il 23 Ago 2020
You can also use
col_index = 1:size(YourArray,1);
row_index = 1:size(YourArray,2);
populated_matrix = 127.5 * cos(pi * row_index(:)) + col_index;
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Language Support in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!