Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Matlab help! Prepare a function m-file containing a function that prints a line

ID: 3763103 • Letter: M

Question



Matlab help!

Prepare a function m-file containing a function that prints a line (to the command window), where the line consists of a string and the values of the elements in a vector. All these components should print on one line with white space between the different components The input will be a structure. The first field will contain the string. The second field will contain the vector of length 4 and of class double. There will be no output variables In the third section of your script m-file, generate a structure array having 2 component structures. You can use any values you want. You will call your function twice. The first time, you will use the first component structure as input. The second time, you will use the second component structure as input.

Explanation / Answer

function structure(s)
    field_name =fieldnames(s);
    val1 =getfield(s, cell2mat(field_name(1,1)));
    val2 =getfield(s, cell2mat(field_name(2,1)));
    fprintf('%s %f %f %f %f ',val1,val2(1),val2(2),val2(3),val2(4));
end

---------------------Test Program-------------------------------------

clc;
clear all;
s1 = struct('f1','Hello','f2',double(rand(4,1)*10));
s2 = struct('f1','Hiiii','f2',double(rand(4,1)*10));
structure(s1);
structure(s2);

-----------------------------Output-----------------------------------------------------

Hello 0.855158 2.624822 8.010146 0.292203
Hiiii 9.288541 7.303309 4.886090 5.785251
>>