how to create 2D matrix and calculate density of each element

조회 수: 12 (최근 30일)
Abdulrehman Khan
Abdulrehman Khan 2017년 7월 24일
댓글: Sayam Ganguly 2017년 7월 25일
I'm new to matlab Can anyone help me out from this problem
- Accept the mass and the volume for 10 different objects labelled from 1 to 10 as 2D matrix.
- Calculate for each object the density using the equation: Density = mass/volume. Store the results in 1D array.
- Find the heaviest and the lightest objects (label and density) and print the results with an appropriate message.
- Generate a report showing the objects’ data (mass, volume, and density) sorted by the density.

답변 (1개)

Sayam Ganguly
Sayam Ganguly 2017년 7월 24일
편집: Sayam Ganguly 2017년 7월 24일
Hi, I understand that you have 10 objects with Mass and Volume that you want to input to the program. Then you want to calculate the density of the objects and display the lightest and heaviest objects. Finally you want generate a report with sorted order of density. I'm assuming that the report would be an excel file. I would like to suggest an approach that should help you achieve this. Below is the code snippet with some instructions -
numInputs = 10;
mv = zeros(numInputs,3);
header = {'Desntiy' 'Label' 'Mass' 'Volume'};
for i = 1:numInputs
mv(i,1) = i;
%Take input from user.
mv(i,2) = input(['Enter Mass for object ' num2str(i) ' : ']);
end
%Use column slicer to access individual columns of the input array to calculate density
%Ex - mv(:,1) will give you the entire first column of the array mv
% Then generate the 1-d density matrix using'./' operator which performs an element wise division
of two arrays.
% Store the result of division in 1-d array called 'd'
[maxValue,maxLabel] = max(d);
% Similar to the line above also find the corresponding minimum value and index and store them in
%variables
fprintf('Heaviest is object %d with density %f\n',maxLabel,maxValue);
%Similarly show the lightest object
% Now horizontally concatenate 'd' and 'mv' to create the 'output' array
% Use horzcat(Refer to https://www.mathworks.com/help/matlab/ref/horzcat.html)
% for that
% Finally add header to 'Output' and generate excel using xlswrite(Refer https://www.mathworks.com/help/matlab/ref/xlswrite.html)
output = [header;num2cell(sortrows(output,1))];
Hope this helps!
  댓글 수: 2
Abdulrehman Khan
Abdulrehman Khan 2017년 7월 24일
thanks for helping but there some error has occurred.
Sayam Ganguly
Sayam Ganguly 2017년 7월 25일
Yes you have to create the matrix 'd' by dividing the two columns of 'mv'. The entire code is not present in the answer. Follow the instructions in the comments and you should be able to complete the code.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by