let us create a variable for a row vector a = [1, 4, 1, 3, 2, 5, 0] and calculate the mean value of its elements using the Matlab function ‘mean’ and store this value in variable aMean. Fig. 1 gives the Matlab code to do this.
a = [1, 4, 1, 3, 2, 5, 0]; aMean = mean(a);
Figure 1: Matlab code – row vector and mean of its elements.
Let us now construct a row vector b that contains the indices of elements of a which are larger than the aMean. The code in Fig. 2 performs this by using a ‘for’ loop. Now, add a line into the code to construct a row vector c that contains the values of elements from a which are larger than the mean of a.
% With a ‘for’ loop j=0; for i=1:length(a),
1 1.1
if a(i)>aMean j=j+1;
b(j)=i;
end end
% add line here to construct the row vector c
Figure 2: Matlab code (‘icme Lab1 vectorMan Sept2020 fin.m’) – manipulation of vectors.
Finally, the code in Fig. 3 perform the same as above but using logical operators and ‘find’ function without any use of ‘for’ loop.
The results should be: aM ean = 2.2857, b = (2, 4, 6), c = (4, 3, 5). 1
% Without a ‘for’ loop b_noLoop = find(a > aMean);
Figure 3: Matlab code – manipulation of vectors (logical operators and ‘find’).
code:
output:
raw_code :
a = [1,4,1,3,2,5,0]; %row vector a
aMean = mean(a); %mean of a
%for loop for finding indices
j=0;
for i=1:length(a)
if(a(i)>aMean)
j=j+1;
b(j) = i;
end
end
%to construct the row vector c
c = a(b)
code :
output :
raw_code :
a = [1,4,1,3,2,5,0]; %given data
aMean = mean(a);
b = find(a>aMean); %to find indices without loop
c = a(b)
**do comment for queries and rate me up******
Get Answers For Free
Most questions answered within 1 hours.