how to solve coding issue

Hello everyone
I have faced a problem in applying a code using my data
I don't know where is the problem in my code or data?
can anyone help

13 Comments

Without seeing a small sample of code and data and a clearer description of the problem you're facing, it's likely going to be difficult if not impossible to offer any help. Show us the code and/or data and ask a specific question about where you're experiencing difficulty and describe what's not working and we may be able to offer more guidance.
  • Do you receive warning and/or error messages? If so the full and exact text of those messages (all the text displayed in orange and/or red in the Command Window) may be useful in determining what's going on and how to avoid the warning and/or error.
  • Does your code do something different than what you expected? If so, what did it do and what did you expect it to do?
  • Did MATLAB crash? If so please send the crash log file (with a description of what you were running or doing in MATLAB when the crash occured) to Technical Support so we can investigate.
Radwan
Radwan on 2 Jul 2024
Edited: Radwan on 2 Jul 2024
Thank you very much.
Very sorry for the delay in replying something came up. So, I couldn't proceed with you.
However, I am still a beginner to use MATLAB
I just want to ask how to share a sample of my data here?
Is there a code can be used to extract an example of the data
please guide me
Otherwise I can share with you the datafile and code as well
best,
When you write a comment, click the paper clip button in the Insert section of the toolstrip above the edit box where you write the comment. That will let you attach a data file (MAT-file, image file, spreadsheet, etc.) to your post.
For code, just copy and paste a small segment into the edit box. Before you do, click the first icon in the Code section of the toolstrip and paste the code into the area that adds in the edit box. Doing so will format the code the same way it's formatted in the MATLAB Editor.
And of course don't forget to ask a specific question once you've attached your data and included your code.
Thank you for clear instrocutions
Here I have attached the the data file
Below is the code I develpoed
%modify historical decomposition
datetick=1:20:230;
datelabel=2000:5:2024;
varnames={'Date','GDP','Consumption','Investment','Employment','Inflation','Interest_Rate','Unemployment','Exchange_Rate'};%y g c inve em inf inr uem
for i=14:22
figgcf=figure(i);
axes_handles=findobj(figgcf,'type','axes');
axsgca=axes_handles(2);
set(axsgca,'XTick',datetick,'XTickLabel',datelabel,'XGrid','on');
axsgca.Title.String=varnames(i-13);
axsgca.XLabel.String='Date';
axsgca.YLabel.String='Percentage';
end
Index exceeds the number of array elements. Index must not exceed 0.
%modify IRF
for i=5:11
figgcf=figure(i);
axes_handles=findobj(figgcf,'type','axes');
for j=1:length(axes_handles)
axescur=axes_handles(j);
set(axescur.Children(1),'LineWidth',2,'Color','red');
set(axescur,'XGrid','on','YGrid','on');
end
end
%plot CVD
varname=oo_.var_list;
exoname=M_.exo_names;
xtick1=1:1:4;
xlabel1={'Q1';'Q4';'Q20';'Q40'};
for i=1:9
contrib1=oo_.conditional_variance_decomposition(i,:,:);
contrib2=squeeze(contrib1);
contrib3=100*contrib2;
fig1=figure;
hold on;
axe1=bar(contrib3,'stacked');
set(gca,'XTick',xtick1,'XTickLabel',xlabel1,'YGrid','on');
xlim([0.5,4.5]);
legend(exoname,'Location','southeastoutside');
title(varnames(i),'FontSize',16);
hold off;
end
Kindly, Be patient with me
I am at the very beginning to learn MatLAb
I hope you fix the code or data
Looking forward to hearing from you
Bes,
Thank you very much for editing
I didn't know how to do it properly
Thanks a lot
@Radwan: You're welcome!
As Steven Lord said, "click the first icon in the Code section of the toolstrip and paste the code into the area that adds in the edit box." The icon is circled in green below:
I also ran your code (using the green triangular button in the Run section of the toolstrip). As you can see in your comment above, the code produces the error "Index exceeds the number of array elements. Index must not exceed 0." This is because the code expects figure 14 to have at least two axes. The problem is that, if figure 14 doesn't exist before the code is run, then the code creates it, but when a figure is created is has no axes.
That brings up the questions: What is the code intended to do? Does the code assume the existence of pre-existing figures with certain properties? How is the code related to the data file you shared? What is the variable "oo_" in the code? But the most important question is: What happens when you run the code that you would like help with?
basically
It's for new kenysian dsge model
I am doing it to see covid 19 shock on the data
Voss
Voss on 2 Jul 2024
Edited: Voss on 2 Jul 2024
What happens when you run the code that you would like help with? Do you get an error? If so, what is the error? Is the behavior not as expected? If so, explain how so. Etc.
Dear @Voss
What is the variable "oo_" in the code?
I actually tried to mimic a given code by the professor
Sorry to say I don't know
The CSV file is simply a table of data. It should be relatively straightforward to plot the selected columns of data.
If you are unfamiliar with your professor's code, I would advise against using it, as it may hinder your ability to learn and make you think that plotting simple data is more difficult in MATLAB than it needs to be. I suggest you plot the desired figure at your own pace. Then, you can learn how to make a bar graph by referring to some examples:
By working through the examples yourself, you will gain a better understanding of the bar() function and how to customize the plot to your needs.
T = readtable("usmodel_data.csv", VariableNamingRule="preserve")
T = 97x9 table
Date GDP Consumption Investment Employment Inflation Interest_Rate Unemployment Exchange_Rate __________ _____ ___________ __________ __________ _________ _____________ ____________ _____________ 2000-01-01 13878 6618.2 2351.2 334 170.1 5.6767 4.0333 32.976 2000-04-01 14131 6711.9 2490.5 334 171.43 6.2733 3.9333 32.841 2000-07-01 14145 6820 2466.4 335 173 6.52 4 33.118 2000-10-01 14230 6918.6 2471.5 334 174.23 6.4733 3.9 33.748 2001-01-01 14183 6995.3 2359 333 175.9 5.5933 4.2333 36.247 2001-04-01 14272 7042.2 2362.7 336 177.13 4.3267 4.4 37.565 2001-07-01 14215 7070.3 2311.4 338 177.63 3.4967 4.8333 37.236 2001-10-01 14254 7187.3 2196.6 340 177.5 2.1333 5.5 37.936 2002-01-01 14373 7217.7 2262.1 341 178.07 1.7333 5.7 40.517 2002-04-01 14461 7308 2298.9 339 179.47 1.75 5.8333 38.85 2002-07-01 14520 7397.1 2296 337 180.43 1.74 5.7333 36.656 2002-10-01 14538 7473 2293.7 336 181.5 1.4433 5.8667 37.613 2003-01-01 14614 7567.1 2312.5 335 183.37 1.25 5.8667 36.594 2003-04-01 14744 7661.5 2327.5 338 183.07 1.2467 6.1333 36.499 2003-07-01 14989 7820.9 2411.6 337 184.43 1.0167 6.1333 36.149 2003-10-01 15163 7913.5 2493.9 337 185.13 0.99667 5.8333 33.629
%% extract data from table
x = T{:,1}; % data on x-axis
y = T{:,2}; % data on y-axis
%% make a simple plot to see how it looks like
plot(x, y), grid on
xlabel('Year')
ylabel('GDP')
%% make a bar graph
xx = 2000:2023;
yy = reshape(y(1:96), 4, 24)'; % Group 4 quarters in one
bar(xx, yy), grid on
xlabel('Year')
ylabel('GDP')
Thank you very very much for these codes. It helps a lot
Actually that style of codes given by the professor is neccesary for the requirement.
So, I will share with you all the data given by the professor to help me figure out the mistakes in my code for my data. I hope this would help
Your professor's code appears to be incomplete. If you insist on using it, we will not be able to assist with the missing parts, as they are user-defined variables (i.e., specific to your professor's implementation), not MATLAB functions.
In fact, there are several concepts in the code that you would need to learn, such as cell arrays like varnames and xlabel1, structure arrays like oo_.var_list and M_.exo_names, the use of for loops, and various MATLAB functions with miscellaneous name-value arguments and structure fields.
@Steven Lord and @Voss have explained some of these in their answer and comment. If the learning process is inflexible for you and you need to submit the code to your professor for evaluation, then you will need to familiarize yourself with all of these aspects before you can get the code working and identify the missing pieces.
Can you provide a list of what these different elements in the code do? This would demonstrate your effort and determination to understand the material, which could be helpful as you move forward.
figure()
findobj()
length()
set()
String
Children
LineWidth
Color
XGrid
YGrid
squeeze()
hold on, hold off
bar()
gca
XTick
XTickLabel
xlim()
legend()
title()
I got it @Sam Chak
Thank you very much
I actually did leave that code and I am using yours for graphs
I will look for code for another type of graphs needed
Thank you very much

Sign in to comment.

 Accepted Answer

Just looking at your first for loop there are several problems or suggestions.
for i=14:22
figgcf=figure(i);
This line creates a new figure. Alternately if there is already a figure with that number open, it makes that figure the current figure. But since there is no line of code in the segment you posted that created any figures, this line ought to create a new figure.
axes_handles=findobj(figgcf,'type','axes');
This will return the handle of any[1] axes that exist in the figure you just created. But creating a figure doesn't automatically add an axes to it, so this will return an empty array. That means when you run the next line:
axsgca=axes_handles(2);
you're attempting to access the second element of an array that doesn't have a second element. [axes_handles doesn't even have a first element!] That's obviously not going to work, and that's why MATLAB threw the error you can see in your comment above, "Index exceeds the number of array elements. Index must not exceed 0."
set(axsgca,'XTick',datetick,'XTickLabel',datelabel,'XGrid','on');
If axsgca had been created, this line of code would have worked. Except it probably wouldn't have done what you wanted, since datetick has 12 elements and datelabel has only 5. So your axes would have the labels from datelabel repeated several times.
You may also be interested in the xticks and xticklabels functions.
axsgca.Title.String=varnames(i-13);
axsgca.XLabel.String='Date';
axsgca.YLabel.String='Percentage';
These ought to work, though I'd use the title, xlabel, and ylabel functions rather than directly setting the String property of those objects.
end
One broader problem is that you've created this figure and set properties on the axes (let's assume for sake of argument that you'd created an axes in the figure), but you haven't actually plotted anything. If you were to try to plot after this point, since you haven't turned hold on, MATLAB would reset the properties of the axes. So I'd recommend creating your plots first and then changing the ticks, grid, labels, and title after you've called plot or bar or other plotting functions.
Since you said you're new to MATLAB, I recommend that if you have access to some of the self-paced online courses that you work through them to familiarize yourself with MATLAB. In the Graphics category, the "Explore Data with MATLAB Plots" seems like a good first step, and "How MATLAB Graphics Work" would provide you with more information about more advanced Handle Graphics techniques.
[1] To those who say "But, actually, it's not all ..." I'm ignoring the axes HandleVisibility probability and findall for right now. That's an advanced maneuver.

2 Comments

Thank you very much for explaining all these things.
But I don't how to solve it.
My concern right now to fix this code to work on my data attached
could you please fix the current code
I could "fix" it by removing the attempt to set properties on an axes that doesn't exist. But somehow I don't think that's what you want.
Let's take a step back. In a comment on this answer, add a code block (using the button @Voss showed you.) Inside that code block, write comments (no code) describing the series of steps you want to implement. So if I were writing a code to deal out a poker hand, it would look something like:
% Create or get a deck of cards
% Shuffle the deck of cards
% Deal out five cards from the top of the deck
You don't have to get into all the details of your algorithm, but list the main parts of your workflow in enough detail that someone who isn't familiar with the workflow can at least understand an overview of it. [In the algorithm above I didn't specify what type of shuffle I used, for example.]
Knowing what you're trying to do may help us suggest how to achieve those steps, how to "fix" your code.

Sign in to comment.

More Answers (1)

Hi @Radwan,
It's good to hear that you're making progress. If you encounter any issues with plotting other types of charts, feel free to come back to this thread and copy/paste your code here. Be sure to click on the 'Indentation' icon and the 'Play' icon to run the code and generate any error messages.
Actually, I find the previous plot is a bit cramped for display. You could consider creating a 2-by-2 grid of the bar graphs, as shown below:
T = readtable("usmodel_data.csv", VariableNamingRule="preserve");
%% extract data from table
x = T{:,1}; % data on x-axis
y = T{:,2}; % data on y-axis
%% make 2-by-2 tiles of bar graphs
tL = tiledlayout(2, 2, 'TileSpacing', 'Compact');
nexttile
xx = 2000:2003;
yy = reshape(y(1:16), 4, 4)'; % Group 4 quarters in one
bar(xx, yy), grid on, ylim([0 2.5e4])
nexttile
xx = 2004:2007;
yy = reshape(y(17:32), 4, 4)'; % Group 4 quarters in one
bar(xx, yy), grid on, ylim([0 2.5e4])
nexttile
xx = 2008:2011;
yy = reshape(y(33:48), 4, 4)'; % Group 4 quarters in one
bar(xx, yy), grid on, ylim([0 2.5e4])
nexttile
xx = 2012:2015;
yy = reshape(y(49:64), 4, 4)'; % Group 4 quarters in one
bar(xx, yy), grid on, ylim([0 2.5e4])
xlabel(tL, 'Year')
ylabel(tL, 'GDP')

Categories

Find more on Environment and Settings in Help Center and File Exchange

Tags

Asked:

on 2 Jul 2024

Answered:

on 3 Jul 2024

Community Treasure Hunt

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

Start Hunting!