Thursday 3 October 2013

Interesting Matlab commands

1. Find and replace/extract a number or set of numbers in one command.
x = 1:1:20;
no_greater_than_5 = x( x>5 );
no_equal_to_5 = x( x==5 );
%It works for other conditional operations as well.

2. Find the INDICES of the SOME(based on a condition) numbers in an array.
x = 1:10:200;
ind_of_no_greater_than_5 = find(x>50)

3. Sum those numbers at the selected INDICES.
s = sum(  x ( ind_of_no_greater_than_5 ) )

%%Using these commands, for-loops can be avoided to increase the speed of execution.

4. Updating only the required elements in an array.
ind_to_be_updated = 1:2:100; % (alternate elements);
array(ind_to_be_updated) = array_with_50_numbers;

%This can be used to generated alternate ones and zeros. Like a clock. This is very useful for implementing the digital stuff in Matlab.

5. For storing the array of arrays with different no. of elements -- use structures.
array(1).a = ones(1,10);
array(2).a= ones(1,20);
array(3).a = ones(1,30);
array(4).b = zeros(30,1);

%To collate all the elements 'a' of the entire array use,
arr_total = [array.a]; %combines everything and gives
arr_total = {array.a}; % gives the individual 'a' s sizes








No comments:

Post a Comment