Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's the fastest way to remove or change large number of entries in arrays in MATLAB?
    primarykey
    data
    text
    <p>I want to change a number of values in a 4D array <em>M</em>_ <em>ijkl</em> to NaN using MATLAB. I use <code>find</code> to get the indices <em>i</em> and <em>j</em> that meet a certain condition for <em>k</em> = 2 and <em>l</em> = 4 (in my case it's the <em>y</em> component of a position at time <em>t</em>_4). I now want to set all the entries for these <em>i</em> and <em>j</em> combinations and for all <em>k</em> and <em>l</em> to NaN.</p> <p>I used this method to do it (example by nkjt):</p> <pre><code>% initialise M = zeros(10,10,2,4); % set two points in (:,:,2,4) to be above threshold. M(2,4,2,4)=5; M(6,8,2,4)=5; % find and set to NaN [i,j] = find(M(:,:,2,4) &gt; 4); M(i,j,:,:)= NaN; % count NaNs sum(isnan(M(:))) % returns 32 </code></pre> <p>This method is is very slow as this example illustrates:</p> <pre><code>M = rand(360,360,2,4); threshold = 0.5; % slow and wrong result [i,j] = find(M(:,:,2,4) &gt; threshold); tic; M(i,j,:,:) = NaN; toc; Elapsed time is 54.698449 seconds. </code></pre> <p>Note that the <code>tic</code> and <code>toc</code> don't time the <code>find</code> so that is not the problem.</p> <p>With Rody's and njkt's help I also realized that my method doesn't actually do what I want. I only want to change entries with the combinations <em>i</em> and <em>j</em> i found with <code>find</code> (for all <em>k</em> and <em>l</em>), i.e. <code>[2,4,:,:]</code> and <code>[6,8,:,:]</code>, but <strong>not</strong> <code>[2,8,:,:]</code> and <code>[6,4,:,:]</code>. In the first example <code>sum(isnan(M(:)))</code> should return 16.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload